Minimum Spanning Tree

MediumGraphs
Next
GraphKruskalUnion FindGreedy

Given a connected, undirected, weighted graph, find a spanning tree (a set of edges connecting all nodes without cycles) with the smallest possible total weight, and print that total weight.

Input

Line 1: n and m. Next m lines: u v w, an undirected edge between nodes u and v (0-based) with weight w.

Output

Print the total weight of a minimum spanning tree.

Constraints

1 <= n <= 1000 n - 1 <= m <= 5000 1 <= w <= 10^4 The graph is connected.

Example 1
Input
4 5
0 1 1
0 2 4
1 2 2
1 3 6
2 3 3
Output
6

Take edges 1, 2 and 3 for a total weight of 6.

Hints

Minimum Spanning Tree - Medium Graphs Problem | Skill Shiksha