#include #include #include #include class UnionFind { std::vector m_root; std::vector m_depth; std::vector m_size; public: UnionFind(int size) : m_root(size), m_depth(size, 0), m_size(size, 1) { std::iota(m_root.begin(), m_root.end(), 0); } void unite(int x, int y) { x = root(x); y = root(y); if(x == y) { return; } auto t = size(x) + size(y); m_size[x] = m_size[y] = t; if(m_depth[x] < m_depth[y]) { m_root[x] = y; } else { m_root[y] = x; } if(m_depth[x] == m_depth[y]) { ++m_depth[x]; } } bool isSame(int x, int y) { return root(x) == root(y); } int root(int x) { if(m_root[x] == x) { return x; } return m_root[x] = root(m_root[x]); } int size(int x) { if(m_root[x] == x) { return m_size[x]; } return size(m_root[x] = root(m_root[x])); } }; using ll = long long; using std::cout; using std::cin; constexpr char endl = '\n'; signed main() { ll n, m; cin >> n >> m; std::vector> cv(n); for(int _ = 0; _ < n; ++_) { ll b, c; cin >> b >> c; cv[c - 1].emplace_back(b - 1); } auto dsu = UnionFind(m); ll ans = 0; for(const auto& dq : cv) if(!dq.empty()) { auto base = dq.front(); for(const auto& tg : dq) { if(!dsu.isSame(base, tg)) { dsu.unite(base, tg); ++ans; } } } cout << ans << endl; }