N,M=map(int,input().split()) l=[[] for i in range(N)] for i in range(N): b,c=map(int,input().split()) b-=1 c-=1 l[c].append(b) root=[i for i in range(M)] height=[0]*M def find(a): f=a if a==root[a]: return a while a!=root[a]: a=root[a] root[f]=a return a def union(a,b): A=find(a) B=find(b) if A==B: return if height[A]>height[B]: root[B]=root[A] return 1 else: root[A]=root[B] if height[A]==height[B]: height[B]+=1 return 1 ans=0 for i in l: if len(i)<2: continue S=i[0] for j in range(1,len(i)): ans+=union(i[j],S) print(ans)