from collections import deque N,M = map(int,input().split()) G = {i:[] for i in range(1,N+M+1)} for _ in range(N): b,c = map(int,input().split()) G[b].append(M+c) G[M+c].append(b) col = [-1]*(N+M+1) cur = 0 for i in range(1,N+M+1): if col[i]<0: col[i] = cur que = deque([i]) while que: j = que.popleft() for k in G[j]: if col[k]<0: col[k] = cur que.append(k) cur += 1 cnt = set() for i in range(1,M+1): cnt.add(col[i]) print(M-len(cnt))