Problem 169
Minimum Spanning Tree
Medium · 20 pts · Graph, Minimum Spanning Tree, Union Find
Problem
You are given a connected undirected graph with N nodes and M weighted edges. A spanning tree is a set of N - 1 edges that connects all the nodes without forming a cycle. Print the total weight of a minimum spanning tree, the spanning tree with the smallest possible total weight. Kruskal's algorithm: sort the edges by weight and add them one by one, skipping any edge whose two ends are already connected (checked with union-find). Prim's algorithm with a priority queue also works. The total can exceed the 32-bit range.
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v w with weight w.
Output
Print the weight of the minimum spanning tree.
Constraints
1 <= N <= 100000; N - 1 <= M <= 200000; 1 <= w <= 1000000; the graph is connected
Example input
4 5 1 2 1 2 3 2 3 4 3 1 4 10 1 3 5
Example output
6
Explanation
Taking the cheapest edges first: 1-2 (weight 1), then 2-3 (weight 2), then 3-4 (weight 3). These already connect all 4 nodes, so 1-3 and 1-4 are not needed. The total weight is 1 + 2 + 3 = 6.