Problem 3: Optimize Water Distribution in a Village
public int minCostToDistributeWater(int n, int[] wells, int[][] pipes) {
List<int[]> allEdges = new ArrayList<>();
addAddEdges(n, wells, pipes, allEdges);
return kruskals(n, allEdges);
}
private int kruskals(int n, List<int[]> allEdges) {
// step 1: sort all the edges
Collections.sort(allEdges, (a,b) -> Integer.compare(a[2], b[2]));
int minCost = 0;
int processedEdges = 0;
// step 2: apply kruskals
UnionFind uf = new UnionFind(n + 1);
for (int[] edge: allEdges) {
//其实也可以改变unionfind里的union这个方法,本题已经apply
int u = edge[0];
int v = edge[1];
int weight = edge[2];
if (uf.union(u, v)) {
preocessedEdges++;
minCost += weight;
if (precessedEdges == n) { // 保证n个村有水
break;
}
}
}
return minCost;
}
private void addAddEdges(int n, int[] wells, int[][] pipes, List<int[]> allEdges) {
// 所有从水源出去的边全部搞定
for (int i = 0; i < n; i++) {
allEdges.add(new int[]{0, i + 1, wells[i]});
}
for(int[] pipe: pipes) {
addEdges.add(pipe);
}
}Last updated