from atcoder.dsu import DSU N, M = map(int, input().split()) dsu = DSU(M) E = [[] for _ in range(N)] for i in range(N): b, c = map(int, input().split()) b -= 1 c -= 1 E[c].append(b) for i in range(N): if len(E[i]) > 1: e0 = E[i][0] for e in E[i][1:]: dsu.merge(e0, e) ans = 0 for i in range(M): if dsu.leader(i) == i: ans += dsu.size(i) - 1 print(ans)