#include #include #include #include #include struct Point { size_t x; size_t y; friend bool operator <(const Point&a, const Point&b) { if (a.x == b.x) return a.y < b.y; return a.x < b.x; } }; int main() { size_t num = 0; std::cin >> num; std::set nodes; std::map> xneigh; std::map> yneigh; for (size_t i = 0; i < num; i++) { Point p; std::cin >> p.x >> p.y; nodes.insert(p); xneigh[p.x].push_back(p); yneigh[p.y].push_back(p); } std::queue to_visit; Point first = *nodes.begin(); to_visit.push(first); nodes.erase(first); size_t total_count = 0; while (!to_visit.empty()) { Point node = to_visit.front(); to_visit.pop(); for (const auto &neigh : xneigh[node.x]) { if (neigh.y != node.y && nodes.count(neigh)) { to_visit.push(neigh); } nodes.erase(neigh); } for (const auto &neigh : yneigh[node.y]) { if (neigh.x != node.x && nodes.count(neigh)) { to_visit.push(neigh); } nodes.erase(neigh); } if (to_visit.empty() && !nodes.empty()) { total_count += 1; to_visit.push(*nodes.begin()); } } std::cout << total_count << std::endl; }