1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class UF { public: vector<int> f; vector<int> size; int n; int setCount; UF(int _n): n(_n), setCount(_n), f(_n), size(_n, 1) { iota(f.begin(), f.end(), 0); } int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); } bool _union(int x, int y) { x = find(x); y = find(y); if (x == y) return false; if (size[x] < size[y]) swap(x, y); f[y] = x; size[x] += size[y]; --setCount; return true; } }; class Solution { public: int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) { UF ufa(n + 1), ufb(n + 1); int ans = 0; for (const auto& edge : edges) if (edge[0] == 3) if (!ufa._union(edge[1], edge[2])) ++ans; else ufb._union(edge[1], edge[2]); for (const auto& edge : edges) if (edge[0] == 1) { if (!ufa._union(edge[1], edge[2])) ++ans; } else if (edge[0] == 2) { if (!ufb._union(edge[1], edge[2])) ++ans; } if (ufa.setCount != 2 || ufb.setCount != 2) return -1; return ans; } };
|