class UnionFind: def __init__(self, n): self.par = [-1]*n self.rank = [0]*n def Find(self, x): if self.par[x] < 0: return x else: self.par[x] = self.Find(self.par[x]) return self.par[x] def Unite(self, x, y): x = self.Find(x) y = self.Find(y) if x != y: if self.rank[x] < self.rank[y]: self.par[y] += self.par[x] self.par[x] = y else: self.par[x] += self.par[y] self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def Same(self, x, y): return self.Find(x) == self.Find(y) def Size(self, x): return -self.par[self.Find(x)] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) B = [[] for i in range(m)] C = [[] for i in range(n)] for i in range(n): b, c = map(int, input().split()) b, c = b-1, c-1 B[b].append(i) C[c].append(i) uf = UnionFind(n) for i in range(m): if len(B[i]) <= 1: continue for j in range(len(B[i])-1): uf.Unite(B[i][j], B[i][j+1]) ans = 0 for i in range(n): if len(C[i]) <= 1: continue for j in range(1, len(C[i])): if not uf.Same(C[i][0], C[i][j]): ans += 1 uf.Unite(C[i][0], C[i][j]) print(ans)