#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define int ll
typedef long double ld;
typedef vector<int> vi;
#define vec vector
#define pii pair<int, int>

#define rep(i, a, b) for(int i = a; i < b; i++)
#define all(x) begin(x), end(x)
#define sz(x) (int)x.size()
#define setmin(x, y) x = min(x, y)
#define setmax(x, y) x = max(x, y)
#define ff first
#define ss second

signed main() {
	int n; cin >> n;
	vec<pii> pnts(n);
    map<int, vi> row, col;
    map<int, bool> rowvis, colvis;
	rep(i, 0, n) {
		int x, y; cin >> x >> y;
		row[x].push_back(i);
        col[y].push_back(i);
        pnts[i] = {x, y};
	}
    vec<bool> vis(n);
    int res = 0;
    rep(i, 0, n){
        if(!vis[i]) {
            res++;
            queue<int> q({i});
            vis[i] = 1;
            while(q.size()) {
                int a = q.front(); q.pop();
                
                if(rowvis[pnts[a].ff] == false)
                for(int p : row[pnts[a].ff]) {
                    if(p == a || vis[p]) continue;
                    vis[p] = 1;
                    q.push(p);
                }

                if(colvis[pnts[a].ss] == false)
                for(int p : col[pnts[a].ss]) {
                    if(p == a || vis[p]) continue;
                    vis[p] = 1;
                    q.push(p);
                }
                rowvis[pnts[a].ff] = true;
                colvis[pnts[a].ss] = true;
            }

        }
    }
    cout << res - 1 << "\n";
}