import sys from collections import defaultdict class UnionFind: def __init__(self, size): self.parent = list(range(size + 1)) # 1-based indexing self.rank = [0] * (size + 1) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): x_root = self.find(x) y_root = self.find(y) if x_root == y_root: return if self.rank[x_root] < self.rank[y_root]: self.parent[x_root] = y_root else: self.parent[y_root] = x_root if self.rank[x_root] == self.rank[y_root]: self.rank[x_root] += 1 def main(): input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr += 1 M = int(input[ptr]) ptr += 1 color_b = defaultdict(set) # color c -> set of boxes box_c = defaultdict(set) # box b -> set of colors for _ in range(N): b = int(input[ptr]) ptr += 1 c = int(input[ptr]) ptr += 1 color_b[c].add(b) box_c[b].add(c) # Initialize Union-Find for colors up to N uf = UnionFind(N) # Connect all colors within the same box for b in box_c: colors = list(box_c[b]) if len(colors) < 2: continue root = colors[0] for c in colors[1:]: uf.union(root, c) # Count the number of boxes per group counter = defaultdict(int) for b in box_c: colors = box_c[b] # Get any color in the box and find its root c = next(iter(colors)) root = uf.find(c) counter[root] += 1 # Calculate the answer ans = sum(k - 1 for k in counter.values()) print(ans) if __name__ == '__main__': main()