#include #include #include int main() { std::map linComp; std::map colComp; std::map compSiz; std::map> compLin; std::map> compCol; int nextComp = 1; int headCnt; std::cin >> headCnt; for (int i = 0; i < headCnt; ++i) { int line, col; std::cin >> line >> col; int firstComp = 0, secondComp = 0; if (linComp.count(line)) firstComp = linComp[line]; if (colComp.count(col)) secondComp = colComp[col]; if (!firstComp && !secondComp) { linComp[line] = nextComp; colComp[col] = nextComp; compSiz[nextComp] = 1; compLin[nextComp] = {line}; compCol[nextComp] = {col}; ++nextComp; } else if (!firstComp && secondComp) { linComp[line] = secondComp; ++compSiz[secondComp]; compLin[secondComp].insert(line); } else if (firstComp && !secondComp) { colComp[col] = firstComp; ++compSiz[firstComp]; compCol[firstComp].insert(col); } else if (firstComp == secondComp) { ++compSiz[firstComp]; } else { int bigger, smaller; if (compSiz[firstComp] > compSiz[secondComp]) { bigger = firstComp; smaller = secondComp; } else { bigger = secondComp; smaller = firstComp; } compSiz[bigger] += compSiz[smaller] + 1; for (int l : compLin[smaller]) { linComp[l] = bigger; compLin[bigger].insert(l); } for (int c : compCol[smaller]) { colComp[c] = bigger; compCol[bigger].insert(c); } compSiz.erase(smaller); compLin.erase(smaller); compCol.erase(smaller); } } std::cout << compSiz.size() - 1 << std::endl; return 0; }