I need some help to figure out union-find problem.
Here is the question.
There's an undirected connected graph with n nodes labeled 1..n. But some of the edges has been broken disconnecting the graph. Find the minimum cost to repair the edges so that all the nodes are once again accessible from each other.
Input:
n, an int representing the total number of nodes.
edges, a list of integer pair representing the nodes connected by an edge.
edgesToRepair, a list where each element is a triplet representing the pair of nodes between which an edge is currently broken and the cost of repearing that edge, respectively
(e.g. [1, 2, 12] means to repear an edge between nodes 1 and 2, the cost would be 12).Example 1:
Input: n = 5, edges = [[1, 2], [2, 3], [3, 4], [4, 5], [1, 5]],
edgesToRepair = [[1, 2, 12], [3, 4, 30], [1, 5, 8]]Output: 20
There are 3 connected components due to broken edges: [1], [2, 3] and [4, 5]. We can connect these components into a single component by repearing the edges between nodes 1 and 2, and nodes 1 and 5 at a minimum cost 12 + 8 = 20.
public int minCostRepairEdges(int N, int[][] edges, int[][] edgesToRepair){
int[] unionFind = new int[N+1];
int totalEdges=0;
for(int[] edge : edges){
int ua = edge[0]; //node1
int ub = edge[1]; //node2
unionFind[ua] = ub;
totalEdges++;
}
//change unionFind for some broken edge
for(int[] broken : edgesToRepair){
int ua = Find(unionFind, broken[0]);
int ub = Find(unionFind, broken[1]);
if(ua == ub){
unionFind[ua] = 0;
}
}
Arrays.sort(edgesToRepair, (a,b)->(a[2]-b[2]));
int cost=0;
for(int[] i : edgesToRepair){
int ua = Find(unionFind, i[0]);
int ub = Find(unionFind, i[1]);
if(ua != ub){
unionFind[ua] = ub;
cost += i[2];
totalEdges++;
}
}
return edgesToRepair==N-1 ? cost : -1;
}
public int find(int[] uf, int find){
if(uf[find]==0) return find;
uf[find] = find(uf, uf[find]);
return uf[find];
}
And Above is my code so far.
My idea is that
First Adding all edges (given edges[][]) to UnionFind and then Update it based on given edgesToRepair Info. (if edge was broken then going to update it in union -find)
Then just try to do basic union-find algorithm to connect two nodes with minimum cost.
Any wrong approach in here?
First, I have trouble updating unionFind when it was broken.
I can't figure out how to handle unbroken edges between two nodes.
Any advice would be helpful.
You're supposed to use Kruskal's algorithm to find a minimum cost spanning tree consisting of the existing edges and broken (repaired) edges:
https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
Just consider the existing edges to have 0 cost, while the broken edges have their repair cost.