This page is still under construction.

Parts of this page are still being built. What you see may change.

City Construction

Interview

Time limit1sMemory limit512 MB

Summary
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 NN (3≤N≤105)(3 \le N \le 10^5 ) and the number of roads MM (2≤M≤min(N(N−1)2,5×105))(2 \le M \le min( {N(N-1) \over 2}, 5×10^5)) .

From the second line to the (M+1)(M + 1)-th line, each line gives the numbers of two buildings aa, bb (1≤a,b≤N,a≠b)(1 \le a, b \le N, a ≠ b) and the cost c(1≤c≤106)c (1 \le c \le 10^6) 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.

Examples3

  1. Example 1

    Input
    7 9
    1 2 15
    2 3 7
    1 3 3
    1 4 8
    3 5 6
    4 5 4
    4 6 12
    5 7 1
    6 7 6
    
    Expected output
    35
    
  2. Example 2

    Input
    8 10
    1 2 4
    2 3 9
    2 4 9
    3 4 4
    3 5 1
    4 6 14
    6 7 5
    5 7 3
    7 8 7
    6 8 3
    
    Expected output
    30
    
  3. Example 3

    Input
    5 4
    1 2 1
    2 3 1
    3 1 1
    4 5 5
    
    Expected output
    -1