class UnionFind(): def __init__(self,n): self.par = [-1] * n self.rank = [0] * n self.siz = [1] * n def root(self,x): if self.par[x] == -1: return x else: self.par[x] = self.root(self.par[x]) return self.par[x] def issame(self,x,y): return self.root(x) == self.root(y) def unite(self,x,y): rx = self.root(x) ry = self.root(y) if rx == ry: return False if self.rank[rx] < self.rank[ry]: rx,ry = ry,rx self.par[ry] = rx if self.rank[rx] == self.rank[ry]: self.rank[rx] += 1 self.siz[rx] += self.siz[ry] return True def size(self,x): return self.siz[self.root(x)] N,M = map(int,input().split()) uf = UnionFind(N+1) L = [[] for i in range(N+1)] for i in range(N): b,c = map(int, input().split()) L[c].append(b) uf = UnionFind(M+1) cnt = 0 for l in L: for c in l: if not uf.issame(l[0],c): uf.unite(l[0],c) cnt+=1 print(cnt)