class UnionFind(): def __init__(self, n): self.n = n self.par = list(range(self.n)) self.rank = [1] * n self.count = n def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def unite(self, x, y): p = self.find(x) q = self.find(y) if p == q: return None if p > q: p, q = q, p self.rank[p] += self.rank[q] self.par[q] = p self.count -= 1 def same(self, x, y): return self.find(x) == self.find(y) def size(self, x): return self.rank[x] def count(self): return self.count n, m = map(int, input().split()) UF = UnionFind(n) bc = [list(map(int, input().split())) for i in range(n)] d = [[] for i in range(n)] for b, c in bc: d[c - 1].append(b - 1) for i in range(n): d[i].sort() ans = 0 for i in range(n): for j in range(len(d[i]) - 1): if UF.same(d[i][j], d[i][j + 1]): continue UF.unite(d[i][j], d[i][j + 1]) ans += 1 print(ans)