#UnionFind from collections import defaultdict class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] n,m=map(int,input().split()) uf=UnionFind(m+1) color=[[] for i in range(n+1)] for _ in range(n): b,c=map(int,input().split()) color[c].append(b) for i in range(n+1): for j in color[i][1:]: uf.union(color[i][0],j) ans=0 for i in uf.roots(): ans+=-uf.parents[i]-1 print(ans)