#include template void print(const T &t) { std::cout << t << '\n'; } template void print(const Head &head, const Tail &... tail) { std::cout << head << ' '; print(tail...); } template using v = std::vector; using ll = long long; using std::cin; struct UnionFind { v parent, rank, count; explicit UnionFind(int n) : parent(n, -1), rank(n, 1), count(n, 1) { } int get_root(int n) { if (parent[n] == -1) { return n; } else { return parent[n] = get_root(parent[n]); } } bool is_same(int i, int j) { return get_root(i) == get_root(j); } void merge(int i, int j) { i = get_root(i); j = get_root(j); if (i == j) { return; } if (rank[i] < rank[j]) { std::swap(i, j); } parent[j] = i; rank[i] = std::max(rank[i], rank[j] + 1); count[i] += count[j]; } }; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int n, m; cin >> n >> m; v col(n, -1); UnionFind uf(m); for (int i = 0; i < n; ++i) { int b, c; cin >> b >> c; b--; c--; if (col[c] != -1) { uf.merge(b, col[c]); } col[c] = b; } int ans = 0; for (auto &i: uf.count) { ans += i - 1; } print(ans); }