|
| 1 | +// Time: O(nlogn) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) { |
| 7 | + vector<tuple<int, int, int>> nodes; |
| 8 | + for (int i = 0; i < wells.size(); ++i) { |
| 9 | + nodes.emplace_back(wells[i], 0, i + 1); |
| 10 | + } |
| 11 | + for (int i = 0; i < pipes.size(); ++i) { |
| 12 | + nodes.emplace_back(pipes[i][2], pipes[i][0], pipes[i][1]); |
| 13 | + } |
| 14 | + sort(nodes.begin(), nodes.end()); |
| 15 | + int result = 0; |
| 16 | + UnionFind union_find(n + 1); |
| 17 | + for (const auto& [c, x, y] : nodes) { |
| 18 | + if (!union_find.union_set(x, y)) { |
| 19 | + continue; |
| 20 | + } |
| 21 | + result += c; |
| 22 | + if (union_find.count() == 1) { |
| 23 | + break; |
| 24 | + } |
| 25 | + } |
| 26 | + return result; |
| 27 | + } |
| 28 | + |
| 29 | +private: |
| 30 | + class UnionFind { |
| 31 | + public: |
| 32 | + UnionFind(const int n) : set_(n), count_(n) { |
| 33 | + iota(set_.begin(), set_.end(), 0); |
| 34 | + } |
| 35 | + |
| 36 | + int find_set(const int x) { |
| 37 | + if (set_[x] != x) { |
| 38 | + set_[x] = find_set(set_[x]); // Path compression. |
| 39 | + } |
| 40 | + return set_[x]; |
| 41 | + } |
| 42 | + |
| 43 | + bool union_set(const int x, const int y) { |
| 44 | + int x_root = find_set(x), y_root = find_set(y); |
| 45 | + if (x_root == y_root) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + set_[min(x_root, y_root)] = max(x_root, y_root); |
| 49 | + --count_; |
| 50 | + return true; |
| 51 | + } |
| 52 | + |
| 53 | + int count() const { |
| 54 | + return count_; |
| 55 | + } |
| 56 | + |
| 57 | + private: |
| 58 | + vector<int> set_; |
| 59 | + int count_; |
| 60 | + }; |
| 61 | +}; |
0 commit comments