#include using namespace std; template bool cmin(A& a, B b) { return a > b && (a = b, true); } template bool cmax(A& a, B b) { return a < b && (a = b, true); } class UnionFind { private: long N; vector PS; public: UnionFind() : N(0) {} UnionFind(long n) : N(n), PS(n, -1) {} bool unite(long a, long b) { long x = root(a), y = root(b); if (x == y) return false; if (-PS.at(x) < -PS.at(y)) swap(x, y); PS.at(x) += PS.at(y); PS.at(y) = x; return true; } bool same(long a, long b) { return root(a) == root(b); } long root(long a) { if (PS.at(a) < 0) return a; return PS.at(a) = root(PS.at(a)); } long size(long a) { return -PS.at(root(a)); } vector> groups() { vector B(N), S(N); for (long i = 0; i < N; i++) { B.at(i) = root(i); S.at(B.at(i))++; } vector> ret(N); for (long i = 0; i < N; i++) { ret.at(i).reserve(S.at(i)); } for (long i = 0; i < N; i++) { ret.at(B.at(i)).push_back(i); } auto f = [&](const vector &v) { return v.empty(); }; ret.erase(remove_if(ret.begin(), ret.end(), f), ret.end()); return ret; } }; signed main() { cin.tie(nullptr)->sync_with_stdio(false); long N, M; cin >> N >> M; vector> V(N); for (long i = 0; i < N; i++) { long a, b; cin >> a >> b, a--, b--; V.at(i) = {a, b}; } UnionFind UF(M); vector> G(N); for (const auto& [a, b] : V) G.at(b).push_back(a); long ans = 0; for (const auto& g : G) { if ((long)g.size() <= 1) continue; long tmp = UF.root(g.front()); for (const auto& a : g) { if (UF.root(a) != tmp) { UF.unite(g.front(), a); ans++; } } } cout << ans << '\n'; }