#K71067. Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm
You are given an undirected graph with \( n \) nodes and \( m \) edges. Each edge is represented by three integers \( u \), \( v \), and \( w \) (with \( u \) and \( v \) as the endpoints and \( w \) as the weight). Your task is to compute the total weight of the Minimum Spanning Tree (MST) of the graph using Kruskal's algorithm.
If the graph is connected (i.e. an MST spanning all nodes exists), output the total weight of the MST. Otherwise, output \( -1 \). In the special case of a single node with no edges, output \( 0 \).
The input is provided via stdin
and the output should be printed to stdout
.
inputFormat
The first line of input contains two integers \( n \) and \( m \) representing the number of nodes and edges, respectively.
Each of the following \( m \) lines contains three integers \( u \), \( v \), and \( w \) representing an edge between nodes \( u \) and \( v \) with weight \( w \).
outputFormat
Output a single integer: the total weight of the MST if the graph is connected, or \( -1 \) if it is not.
## sample4 5
1 2 1
1 3 4
2 3 2
2 4 3
3 4 5
6