#include #include #include #include #include #include #include using ll = long long; int main() { std::cout.tie(nullptr); std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); ll N; std::cin >> N; std::set> heads; std::unordered_map> x_to_y; std::unordered_map> y_to_x; for (ll i = 0; i < N; i += 1) { ll x, y; std::cin >> x >> y; x_to_y[x].push_back(y); y_to_x[y].push_back(x); heads.insert({x, y}); } std::set> visited; ll num_components = -1; std::queue> queue; while (!heads.empty()) { num_components += 1; { auto first_head = *heads.begin(); visited.insert(first_head); queue.push(first_head); heads.erase(first_head); } while (!queue.empty()) { auto [current_x, current_y] = queue.front(); queue.pop(); for (auto &neighbor_y: x_to_y[current_x]) { std::pair neighbour = {current_x, neighbor_y}; if (visited.count(neighbour) != 1) { queue.push(neighbour); visited.insert(neighbour); heads.erase(neighbour); } } for (auto &neighbor_x: y_to_x[current_y]) { std::pair neighbour = {neighbor_x,current_y }; if (visited.count(neighbour) != 1) { queue.push(neighbour); visited.insert(neighbour); heads.erase(neighbour); } } } } std::cout << num_components << std::endl; return 0; }