#include<iostream>
#include<vector>
#include<map>
using namespace std;
#define FF(x, y, z) for(int x =y; x < z; x++)

int main() {
    int n;
    cin >> n;
    map<int, int> rows;
    map<int, int> cols;
    map<int, int> map_id;
    int max_id =1;
    int sum = 0;

    FF(i, 0, n) {
        int x, y;
        cin >> x >> y;
        int row_id = rows[x];
        row_id = map_id[row_id] ? map_id[row_id] :row_id;
        int cols_id = cols[y];
        cols_id = map_id[cols_id] ? map_id[cols_id] :cols_id;
        int cur_id = max_id;
        /*for(auto& [key, val]: map_id) {
            cout << " " << key << ":" << val << ", ";
        }
        cout << endl;
        cout << row_id << " " << cols_id << endl ;*/

        if (row_id != 0 && cols_id != 0 && row_id != cols_id) {
            sum--;
            int from = cols_id;
            int to = row_id;
            cur_id = row_id;
            map_id[from] = to;
            for(auto& [key, val]: map_id) {
                if (val == from) {
                    map_id[key] = to;
                }
            }
            
        }
        else if (row_id || cols_id){
            if (row_id)
                cur_id = row_id;
            else
                cur_id = cols_id;
        }
        else {
            sum++;
            max_id++;
        }
        rows[x] = cur_id;
        cols[y] = cur_id;
    }
    cout << sum -1 << endl;
    return 0;
}

