Prim's Algorithm for Finding the Minimum Spanning Tree
Given an undirected graph with n vertices and m edges, which may contain multiple edges and self-loops, and edge weights may be negative.
Find the sum of the weights of the edges in the minimum spanning tree. If the minimum spanning tree does not exist, output "impossible".
Input Format
The first line contains two integers n and m.
The next m lines each contain three integers u, v, w, indicating that there is an edge between vertex u and vertex v with weight w.
Output Format
One line. If the minimum spanning tree exists, output an integer representing the sum of the weights of the edges in the minimum spanning tree. If the minimum spanning tree does not exist, output "impossible".
Constraints
1 ≤ n ≤ 500
1 ≤ m ≤ 105
The absolute values of the edge weights in the graph do not exceed 10000.
Sample Input
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
Sample Output
6
Comments