class unionfind: def __init__(self,n): self.n = n self.par = [-1]*n self.size = [1]*n def root(self,x): while True: if self.par[x] == -1: return x if self.par[self.par[x]] == -1: return self.par[x] self.par[x] = self.par[self.par[x]] x = self.par[x] def unite(self,u,v): rootu = self.root(u) rootv = self.root(v) if rootu != rootv: if self.size[rootu] < self.size[rootv]: self.par[rootu] = rootv self.size[rootv] += self.size[rootu] else: self.par[rootv] = rootu self.size[rootu] += self.size[rootv] def same(self,u,v): return self.root(u) == self.root(v) def siz(self, x): return self.size[self.root(x)] N, M = map(int,input().split()) b = [None]*N c = [None]*N P = [list() for i in range(N)] for i in range(N): b[i], c[i] = map(int,input().split()) b[i] -= 1 c[i] -= 1 P[c[i]].append(b[i]) uf = unionfind(M) ans = 0 for i in range(N): if len(P[i]) > 1: for x in P[i]: if not uf.same(P[i][0],x): uf.unite(P[i][0],x) ans += 1 print(ans)