- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 85 lines of C++ from the credited upstream file maximize-spanning-tree-stability-with-upgrades.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks 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 maxStability(int n, vector<vector<int>>& edges, int k) {8 UnionFind uf(n);9 int cnt = 0;10 int result = numeric_limits<int>::max();11 for (const auto& e : edges) {12 const auto& u = e[0], &v = e[1], &s = e[2], &m = e[3];13 if (!m) {14 continue;15 }16 if (!uf.union_set(u, v)) {17 return -1;18 }19 ++cnt;20 result = min(result, s);21 }22 sort(begin(edges), end(edges), [](const auto& a, const auto& b) {23 return a[2] > b[2];24 });25 for (const auto& e : edges) {26 const auto& u = e[0], &v = e[1], &s = e[2], &m = e[3];27 if (m) {28 continue;29 }30 if (!uf.union_set(u, v)) {31 continue;32 }33 ++cnt;34 if (cnt == (n - 1) - k) {35 result = min(result, s);36 } else if (cnt == n - 1) {37 result = min(result, 2 * s);38 }39 }40 return cnt == n - 1 ? result : -1;41 }42 43private:44class UnionFind {45 public:46 UnionFind(int n)47 : set_(n)48 , rank_(n) { 49 iota(begin(set_), end(set_), 0);50 }51 52 int find_set(int x) {53 vector<int> stk;54 while (set_[x] != x) { 55 stk.emplace_back(x);56 x = set_[x];57 }58 while (!empty(stk)) {59 const int y = stk.back(); stk.pop_back();60 set_[y] = x;61 }62 return x;63 }64 65 bool union_set(int x, int y) {66 x = find_set(x), y = find_set(y);67 if (x == y) {68 return false;69 }70 if (rank_[x] > rank_[y]) {71 swap(x, y);72 }73 set_[x] = y; 74 if (rank_[x] == rank_[y]) {75 ++rank_[y];76 }77 return true;78 }79 80 private:81 vector<int> set_;82 vector<int> rank_;83 };84};85