fork download
  1. #include <bits/stdc++.h>
  2. #define int long long
  3.  
  4. using namespace std;
  5.  
  6. struct info {
  7. int x, y;
  8. };
  9.  
  10. int n;
  11. vector<info> snow(1111);
  12. bool visited[1111];
  13.  
  14. void BFS(int s) {
  15. queue<int> q;
  16. q.push(s);
  17. visited[s] = true;
  18.  
  19. while (!q.empty()) {
  20. int u = q.front();
  21. q.pop();
  22.  
  23. for (int v = 1; v <= n; v += 1) {
  24. if (!visited[v] && (snow[u].x == snow[v].x || snow[u].y == snow[v].y)) {
  25. visited[v] = true;
  26. q.push(v);
  27. }
  28. }
  29. }
  30. }
  31.  
  32. int32_t main() {
  33. ios_base::sync_with_stdio(false);
  34. cin.tie(NULL);
  35.  
  36. cin >> n;
  37.  
  38. int res = 0;
  39.  
  40. for (int i = 1; i <= n; i += 1) {
  41. cin >> snow[i].x >> snow[i].y;
  42. }
  43.  
  44. for (int i = 1; i <= n; i += 1) {
  45. if (!visited[i]) {
  46. BFS(i);
  47. res += 1;
  48. }
  49. }
  50.  
  51. cout << res - 1;
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
-1