City Construction
InterviewTime limit1sMemory limit512 MB
Given a connected weighted undirected graph, compute the total edge cost minus the cost of a minimum spanning tree, or -1 if the graph is disconnected.
- Level
Medium5 of 10
- Topics
- Minimum spanning tree, Union-find, Graph, Greedy
- Solved
- No attempts yet
Problem
Chaewan drew up a construction plan to build bidirectional roads between buildings in a new city.
While reviewing the plan, he found that the cost was higher than expected.
Chaewan wants to cut the construction cost. He will build only the minimum set of roads so that every building is connected through roads.

The picture above is a map showing the buildings, the roads drawn as straight lines, and the cost of building each road.

Building every road in the picture costs 62. Building only the roads that connect all the buildings costs 27, so the savings are 35.
There are so many roads that Chaewan has trouble working out the savings.
Compute the savings for Chaewan.
Input
The first line gives the number of buildings and the number of roads .
From the second line to the -th line, each line gives the numbers of two buildings , and the cost of building a road between them. No two roads connect the same pair of buildings.
Output
Print how much of the budget can be saved. If not all buildings are connected, print -1.