You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
6
+
7
+
For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes, where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional.
8
+
9
+
Return the minimum total cost to supply water to all houses.
10
+
11
+
Example 1:
12
+
Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
13
+
Output: 3
14
+
Explanation:
15
+
The image shows the costs of connecting houses using pipes.
16
+
The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.
17
+
18
+
Constraints:
19
+
1 <= n <= 104
20
+
wells.length == n
21
+
0 <= wells[i] <= 105
22
+
1 <= pipes.length <= 104
23
+
pipes[j].length == 3
24
+
1 <= house1j, house2j <= n
25
+
0 <= costj <= 105
26
+
house1j != house2j
27
+
*/
28
+
29
+
classDSU {
30
+
public:
31
+
vector<int> parent, rank;
32
+
33
+
DSU(int n) {
34
+
parent = vector <int> (n+1, 0);
35
+
rank = vector <int> (n+1, 0);
36
+
37
+
for(int i = 0; i <= n; ++i) {
38
+
parent[i] = i;
39
+
rank[i] = 1;
40
+
}
41
+
}
42
+
43
+
intfind(int a) {
44
+
if(parent[a] == a) return a;
45
+
return parent[a] = find(parent[a]);
46
+
}
47
+
48
+
voidjoin(int a, int b) {
49
+
int pa = find(a), pb = find(b);
50
+
if(pa == pb) return;
51
+
52
+
if(rank[pa] > rank[pb]) parent[pb] = pa;
53
+
elseif(rank[pa] < rank[pb]) parent[pa] = pb;
54
+
else {
55
+
parent[pa] = pb;
56
+
rank[pb]++;
57
+
}
58
+
}
59
+
};
60
+
61
+
classSolution {
62
+
public:
63
+
intminCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) {
||[Optimize Water Distribution in a Village](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3834/)|[cpp](./Optimize%20Water%20Distribution%20in%20a%20Village.cpp)|
5
6
| 1. |[Making A Large Island](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3835/)|[cpp](./01.%20Making%20A%20Large%20Island.cpp)|
0 commit comments