- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 59 lines of C++ from the credited upstream file incremental-even-weighted-cycle-queries.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int numberOfEdgesAdded(int n, vector<vector<int>>& edges) {8 int result = 0;9 UnionFind uf(n);10 for (const auto& e : edges) {11 if (uf.union_set(e[0], e[1], e[2])) {12 ++result;13 }14 }15 return result;16 }17 18private:19 class UnionFind {20 public:21 UnionFind(int n)22 : set_(n)23 , rank_(n)24 , parity_(n) { 25 iota(begin(set_), end(set_), 0);26 }27 28 int find_set(int x) {29 if (set_[x] != x) {30 const int root = find_set(set_[x]);31 parity_[x] ^= parity_[set_[x]]; 32 set_[x] = root;33 }34 return set_[x];35 }36 37 bool union_set(int x, int y, int w) {38 const int x0 = x, y0 = y;39 x = find_set(x), y = find_set(y);40 if (x == y) {41 return parity_[x0] ^ w ^ parity_[y0] == 0; 42 }43 if (rank_[x] > rank_[y]) {44 swap(x, y);45 } else if (rank_[x] == rank_[y]) {46 ++rank_[y];47 }48 set_[x] = y; 49 parity_[x] = parity_[x0] ^ w ^ parity_[y0]; 50 return true;51 }52 53 private:54 vector<int> set_;55 vector<int> rank_;56 vector<int> parity_; 57 };58};59