


The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains two single space-separated integers ‘N’ and ‘M’ denoting the number of cities and roads respectively.
Each of the next ‘M’ lines contains three single space-separated integers ‘U’, ‘V’, and ‘W’ denoting a two-way road between city ‘U’ and ‘V’ of cost ‘W’.
For each test case, return an integer denoting the minimum cost.
You don't need to print the output, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
1 <= M <= 10^4
1 <= W <= 10^3
1 <= U, V <= N
Time Limit: 1 sec
The basic idea of this approach is to convert this task into a graph problem. Consider an undirected weighted graph of cities as nodes and roads as edges. Now, we need to find the minimum cost to connect all the cities which is equivalent to finding the minimum spanning tree of the graph.
We can use Kruskal’s Minimum Spanning Tree Algorithm for this task.
Please refer to https://cp-algorithms.com/graph/mst_kruskal.html for a detailed explanation of Kruskal’s Algorithm.
The basic idea of Kruskal’s algorithm is to sort the edges of the graph in non-decreasing order by its weight. And place all the nodes of the original graph isolated from each other, to form a forest of single node trees. Then, at each step of the algorithm, we will try to merge the trees by an edge of the original graph. The idea here is to choose the edges greedily. At each iteration, choose the edge with the minimum weight which is not chosen previously.
While choosing the edge, we will make sure that it doesn’t belong to the same subtrees (because adding that edge will create a cycle).
Let us visualize the algorithm for the first test case of sample test case 1.
The idea here is to use a Disjoint Set Union data structure to solve this task. You can refer to this article from cp-algorithms to read more about DSU. https://cp-algorithms.com/data_structures/disjoint_set_union.html
Since at each step of merging of two subtrees, we need to check if two vertices belong to the same subtrees or not. We can use the FIND_SET() function from DSU to do this task. Then, for performing the merge operation of two subtrees, we can use DSU UNION_SETS(). We will use the union by rank and path compression for optimization.
Now consider the following steps for implementing the algorithm: