Minimum cost to connect cities

Given a city network having A nodes. The Roads of this city are damaged and you are asked to repair the roads.

Given a matrix B of size M x 3 which represents the road such that there is a road between B[i][0] and B[i][1] before the damage and cost of repairing this road is B[i][2]. you need to repair some of the roads with the minimum cost such that the city will get connected after repairing the roads. In other words, after repairing some of the the roads, every pair of the city will be reachable from one another.

Note:

  1. No city was connected to itself before the roads were damaged.

  2. Before the damage of roads, there is only one road between the given pair of roads.

  3. Cities are Numbered from 1 to A.

  4. The city network is connected before the roads are damaged.

  5. Your solution will run on multiple test cases. If you are using global variables make sure to clear them.

Input Format

The first argument given is an integer A.
The second argument given is the matrix B.

Output Format

Return the minimum cost to repair some of the the roads so that the city will get connected.

Constraints

1 <= A <= 100000
1 <= M <= min(100000, (A*(A-1)/2))
1 <= B[i][0], B[i][1] <= A
0 <= B[i][2] <= 10000;

For Example

Input 1:
    A = 5
    B = [   [2, 1, 3]
            [2, 3, 5] 
            [3, 5, 1] 
            [1, 4, 9] 
            [5, 4, 5] 
            [5, 2, 3] 
            [5, 1, 2] 
            [4, 3, 10] ] 
Output 1:
    11

Input 2:
    A = 8
    B = [   [4, 3, 8]
            [3, 2, 6] 
            [2, 7, 9] 
            [7, 5, 2] 
            [5, 6, 10] 
            [7, 8, 1] 
            [4, 1, 2] 
            [8, 6, 2] ]
Output 2:
    30
public class Solution {
    public int solve(int n, int[][] edges) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);
        for (int[] edge : edges) {
            int[] e = new int[] { edge[0] - 1, edge[1] - 1, edge[2] };
            pq.add(e);
        }
        int[] parent = new int[n];
        for (int i = 0; i < n; i++)
            parent[i] = i;
        int cost = 0;
        while (pq.size() != 0) {
            int[] edge = pq.poll();
            int parentX = findParent(parent, edge[0]);
            parent[edge[0]] = parentX;
            int parentY = findParent(parent, edge[1]);
            parent[edge[1]] = parentY;
            if (parentX != parentY) {
                cost += edge[2];
                parent[parentX] = parentY;
            }
        }
        return cost;
    }

    public int findParent(int[] parent, int node) {
        while (parent[node] != node)
            node = parent[node];
        return node;
    }
}

Last updated