OlveraeUNSW
Back to problems
COMP2521

MST: Total Weight

MST: total weight of the minimum spanning tree

Read a weighted undirected connected graph and use Kruskal to compute the MST's total weight. Union-find (find), the edge struct, and sorting (qsort) are provided; you complete Kruskal's main loop.

Method: iterate over the edges sorted by ascending weight; for each (u, v, w): if find(u) != find(v) (different sets, so adding it makes no cycle), union them and add w to total; otherwise skip.

Pitfalls (straight from the bug lab): (1) only add when find(u) != find(v), else you create a cycle and overshoot. (2) Edges must be ascending (qsort already did it); not input order. (3) Merge sets with parent[find(u)] = find(v).

Input

  • Line 1: V E (vertices, edges; the graph is connected).
  • Next E lines: u v w, an undirected edge of weight w.

Output

  • One line: the total weight of the MST.

Example: input 4 4 / 0 1 1 / 1 2 2 / 2 3 3 / 0 3 4 -> 6 (take 1+2+3, skip the cycle-forming 4).

Samples

stdin
4 4
0 1 1
1 2 2
2 3 3
0 3 4
expected
6
stdin
5 7
0 1 2
0 3 6
1 2 3
1 3 8
1 4 5
2 4 7
3 4 9
expected
16
c-dcc
14