import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); HashMap> counts = new HashMap<>(); for (int i = 0; i < n; i++) { int b = sc.nextInt() - 1; int c = sc.nextInt(); if (!counts.containsKey(c)) { counts.put(c, new TreeSet<>()); } counts.get(c).add(b); } int ans = 0; UnionFindTree uft = new UnionFindTree(m); for (TreeSet set : counts.values()) { int x = set.pollFirst(); for (int y : set) { if (!uft.same(x, y)) { ans++; uft.unite(x, y); } } } System.out.println(ans); } static class UnionFindTree { int[] parents; public UnionFindTree(int x) { parents = new int[x]; for (int i = 0; i < x; i++) { parents[i] = i; } } public int find(int x) { if (x == parents[x]) { return x; } else { return parents[x] = find(parents[x]); } } public boolean same(int x, int y) { return find(x) == find(y); } public void unite(int x, int y) { if (!same(x, y)) { parents[find(x)] = find(y); } } } }