class UnionFind: def __init__(self, size): self.data = [-1] * size def root(self, x): if self.data[x] < 0: return x ans = self.root(self.data[x]) self.data[x] = ans return ans def unite(self, x, y): x = self.root(x) y = self.root(y) if x == y: return False if self.data[x] > self.data[y]: x, y = y, x self.data[x] += self.data[y] self.data[y] = x return True def is_root(self, x): return self.data[x] < 0 def size(self, x): return -self.data[self.root(x)] n, m = map(int, input().split(' ')) assert 1 <= n <= 200000 assert 1 <= m <= 200000 uf = UnionFind(n + m) # n + i に色 i の超頂点をおく for i in range(n): b, c = map(int, input().split(' ')) assert 1 <= b <= m assert 1 <= c <= n b -= 1 c -= 1 uf.unite(b, m + c) ans = 0 for i in range(n + m): if uf.is_root(i): ans += uf.size(i) - 1 for i in range(m, m + n): # 超頂点の分足しすぎるので、引く if uf.size(i) > 1: ans -= 1 print(ans)