- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 60 lines of C++ from the credited upstream file minimize-maximum-component-cost.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 minCost(int n, vector<vector<int>>& edges, int k) {8 sort(begin(edges), end(edges), [](const auto& a, const auto& b) {9 return a[2] < b[2];10 });11 int cnt = 0;12 UnionFind uf(n);13 for (const auto& e : edges) {14 if (!uf.union_set(e[0], e[1])) {15 continue;16 }17 if (++cnt == n - k) {18 return e[2];19 }20 }21 return 0;22 }23 24private:25 class UnionFind {26 public:27 UnionFind(int n)28 : set_(n)29 , rank_(n) {30 iota(set_.begin(), set_.end(), 0);31 }32 33 int find_set(int x) {34 if (set_[x] != x) {35 set_[x] = find_set(set_[x]); 36 }37 return set_[x];38 }39 40 bool union_set(int x, int y) {41 x = find_set(x), y = find_set(y);42 if (x == y) {43 return false;44 }45 if (rank_[x] > rank_[y]) {46 swap(x, y);47 }48 set_[x] = y; 49 if (rank_[x] == rank_[y]) {50 ++rank_[y];51 }52 return true;53 }54 55 private:56 vector<int> set_;57 vector<int> rank_;58 };59};60