|
| 1 | +/** |
| 2 | + * 1168. Optimize Water Distribution in a Village |
| 3 | + * https://leetcode.com/problems/optimize-water-distribution-in-a-village/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are n houses in a village. We want to supply water for all the houses by building |
| 7 | + * wells and laying pipes. |
| 8 | + * |
| 9 | + * For each house i, we can either build a well inside it directly with cost wells[i - 1] |
| 10 | + * (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs |
| 11 | + * to lay pipes between houses are given by the array pipes where each |
| 12 | + * pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j |
| 13 | + * together using a pipe. Connections are bidirectional, and there could be multiple valid |
| 14 | + * connections between the same two houses with different costs. |
| 15 | + * |
| 16 | + * Return the minimum total cost to supply water to all houses. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} n |
| 21 | + * @param {number[]} wells |
| 22 | + * @param {number[][]} pipes |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var minCostToSupplyWater = function(n, wells, pipes) { |
| 26 | + const edges = []; |
| 27 | + |
| 28 | + for (let i = 0; i < n; i++) { |
| 29 | + edges.push([0, i + 1, wells[i]]); |
| 30 | + } |
| 31 | + |
| 32 | + for (const [house1, house2, cost] of pipes) { |
| 33 | + edges.push([house1, house2, cost]); |
| 34 | + } |
| 35 | + |
| 36 | + edges.sort((a, b) => a[2] - b[2]); |
| 37 | + |
| 38 | + const parent = Array.from({ length: n + 1 }, (_, i) => i); |
| 39 | + let result = 0; |
| 40 | + let edgesUsed = 0; |
| 41 | + |
| 42 | + for (const [from, to, cost] of edges) { |
| 43 | + if (union(from, to)) { |
| 44 | + result += cost; |
| 45 | + edgesUsed++; |
| 46 | + if (edgesUsed === n) break; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | + |
| 52 | + function find(x) { |
| 53 | + if (parent[x] !== x) { |
| 54 | + parent[x] = find(parent[x]); |
| 55 | + } |
| 56 | + return parent[x]; |
| 57 | + } |
| 58 | + |
| 59 | + function union(x, y) { |
| 60 | + const rootX = find(x); |
| 61 | + const rootY = find(y); |
| 62 | + if (rootX !== rootY) { |
| 63 | + parent[rootX] = rootY; |
| 64 | + return true; |
| 65 | + } |
| 66 | + return false; |
| 67 | + } |
| 68 | +}; |
0 commit comments