#include using namespace std; #define ll long long void testcase() { ll n, components = 0; cin >> n; map, vector>> neighbors; // true -> is column for(ll i = 0; i < n; ++i) { ll x, y; cin >> x >> y; neighbors[{x, false}].push_back({y, true}); neighbors[{y, true}].push_back({x, false}); } while(!neighbors.empty()){ deque> q; set> v; v.insert(neighbors.begin()->first); q.push_back(neighbors.begin()->first); while(!q.empty()) { auto current = q.front(); q.pop_front(); // cout << current.first << " " << current.second << " " << components << "\n"; for(auto& x: neighbors[current]) { if(v.find(x) != v.end()) continue; v.insert(x); q.push_back(x); } neighbors.erase(current); } components++; } cout << components - 1 << "\n"; } int main() { testcase(); }