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
| class Solution { public: int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) { vector<tuple<int, int, int>> edges; for (int i = 0; i < n; ++i) { edges.emplace_back(wells[i], 0, i + 1); } for (const auto &p : pipes) { edges.emplace_back(p[2], p[0], p[1]); } sort(begin(edges), end(edges)); parent.resize(n + 1); iota(begin(parent), end(parent), 0); int res = 0; for (const auto &[w, u, v] : edges) { if (merge(u, v)) { res += w; } } return res; }
int find(int x) { while (x != parent[x]) { x = parent[x] = parent[parent[x]]; } return x; }
bool merge(int x, int y) { int px = find(x), py = find(y); if (px == py) return false; parent[px] = py; return true; }
vector<int> parent; };
|