Problem 636
Second Minimum Spanning Tree
Hard · 30 pts · Graph, Minimum Spanning Tree, Union Find
Problem
A connected undirected weighted graph is given. Find the smallest total weight of a spanning tree that is strictly heavier than the minimum spanning tree, or print -1 if every spanning tree has the minimum weight. Build an MST with Kruskal's algorithm. Every other spanning tree candidate swaps one non-tree edge (u, v, w) in for a tree edge on the u-v path; to increase the total strictly, remove the heaviest path edge whose weight is below w.
Input
The first line contains N and M. Each of the next M lines contains an edge u v w.
Output
Print the weight of the second-best spanning tree, or -1.
Constraints
2 <= N <= 200; N - 1 <= M <= 2000; 1 <= w <= 10^6; no self-loops or parallel edges; the graph is connected
Example input
3 3 1 2 1 2 3 2 1 3 3
Example output
4
Explanation
In the triangle with edges 1-2 (weight 1), 2-3 (weight 2) and 1-3 (weight 3), the MST uses weights 1 and 2 (total 3). The next spanning trees weigh 1 + 3 = 4 and 2 + 3 = 5, so the answer is 4.