leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2316.cpp (1039B)


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