2316.cpp (1039B)
1 class UnionFind { 2 int n, cnt = n; 3 vector<int> root, size; 4 5 public: 6 UnionFind(int n) : n(n), root(n), size(n, 1) { iota(root.begin(), root.end(), 0); } 7 8 int find(int x) { 9 while (x != root[x]) 10 x = root[x] = root[root[x]]; 11 return x; 12 } 13 14 void join(int x, int y) { 15 x = find(x), y = find(y); 16 if (x != y) { 17 if (size[x] > size[y]) swap(x, y); 18 root[x] = y; 19 size[y] += size[x]; 20 cnt--; 21 } 22 } 23 24 int count() { return cnt; } 25 bool connected(int x, int y) { return find(x) == find(y); } 26 27 long long count_unreachable() { 28 long long res = 0; 29 30 for (int i = 0; i < n; i++) 31 if (root[i] == i) res += (long long)size[i] * (n - size[i]); 32 33 return res / 2; 34 } 35 }; 36 37 class Solution { 38 public: 39 long long countPairs(int n, vector<vector<int>> &edges) { 40 UnionFind uf(n); 41 for (auto &e : edges) 42 uf.join(e[0], e[1]); 43 return uf.count_unreachable(); 44 } 45 };