class UnionFind: def __init__(self, n): self.parent = [-1] * n self.size = [1] * n def find(self, x): if self.parent[x] == -1: return x self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): px = self.find(x) py = self.find(y) if px == py: return if self.size[px] < self.size[py]: px, py = py, px self.parent[py] = px self.size[px] += self.size[py] def same(self, x, y): return self.find(x) == self.find(y) def get_size(self, x): return self.size[self.find(x)] def get_all_groups(self): n = len(self.parent) groups = [[] for _ in range(n)] for i in range(n): groups[self.find(i)].append(i) return list(filter(lambda x: x, groups)) N, M = map(int, input().split()) G = [[] for _ in range(N+1)] for _ in range(N): b, c = map(int, input().split()) G[c].append(b) uf = UnionFind(M+1) ans = 0 for col in G: for box in col: if not uf.same(col[0], box): uf.union(col[0], box) ans += 1 print(ans)