#include using namespace std; typedef long long ll; typedef pair pll; typedef long double ld; typedef pair pdd; #define vec vector #define For(i, a, n) for(ll i=(ll)a;i pairoperator+(const pair&a, const pair&b){ return {a.first + b.first, a.second + b.second}; } template ostream&operator<<(ostream&os, const pair&c){ return os<<"("< basic_ostream&operator<<(basic_ostream&os, const C&c){ for(auto itr=begin(c);itr!=end(c);++itr){ os<<(itr==begin(c)?"":" ")<<*itr; } return os; } template void dbg(Args&&...args){ ((cerr<> n; vector,ll>> xy(n); vector,ll>> yx(n); For(i,0,n){ ll x,y; cin >> x >> y; xy[i] = {{x,y},i}; yx[i] = {{y,x},i}; } sort(xy.begin(),xy.end()); sort(yx.begin(),yx.end()); vector> neighbors(n); ll last = xy[0].first.first-1; For(i,0,n){ if(xy[i].first.first == last){ neighbors[xy[i].second].push_back(xy[i-1].second); neighbors[xy[i-1].second].push_back(xy[i].second); }else{ last = xy[i].first.first; } } last = yx[0].first.first-1; For(i,0,n){ if(yx[i].first.first == last){ neighbors[yx[i].second].push_back(yx[i-1].second); neighbors[yx[i-1].second].push_back(yx[i].second); }else{ last = yx[i].first.first; } } ll result = -1; vector done(n,false); For(i,0,n){ if(done[i]){ continue; } result++; queue frontier; frontier.push(i); done[i] = true; while(!frontier.empty()){ ll now = frontier.front(); frontier.pop(); For(child,0,neighbors[now].size()){ if(!done[neighbors[now][child]]){ done[neighbors[now][child]] = true; frontier.push(neighbors[now][child]); } } } } cout << result << "\n"; } int main(){ cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); int t = 1; while(t--)solve(); return 0; }