Skip to content

Commit 0d85c0b

Browse files
authored
Create 1168-optimize-water-distribution-in-a-village.js
1 parent cc1ba7f commit 0d85c0b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[]} wells
4+
* @param {number[][]} pipes
5+
* @return {number}
6+
*/
7+
const minCostToSupplyWater = function(n, wells, pipes) {
8+
const uf = Array(n + 1).fill(0)
9+
const edges = []
10+
for(let i = 0; i < n; i++) {
11+
uf[i + 1] = i + 1
12+
edges.push([0, i + 1, wells[i]])
13+
}
14+
for(let p of pipes) {
15+
edges.push(p)
16+
}
17+
edges.sort((a, b) => a[2] - b[2])
18+
let res = 0
19+
for(let e of edges) {
20+
const x = find(e[0]), y = find(e[1])
21+
if(x !== y) {
22+
res += e[2]
23+
uf[x] = y
24+
n--
25+
}
26+
}
27+
return res
28+
29+
function find(x) {
30+
if(x !== uf[x]) uf[x] = find(uf[x])
31+
return uf[x]
32+
}
33+
};

0 commit comments

Comments
 (0)