Bad Cowtractors

Interview

Time limit1sMemory limit128 MB

Summary
Given an undirected weighted graph, find a spanning tree of maximum total edge cost, or report -1 if no spanning tree exists.
Level

Medium4 of 10

Topics
Minimum spanning tree, Greedy, Graph, Sorting
Solved
No attempts yet

Statement

Bessie has been hired to build a cheap internet network among Farmer John's NN (2≤N≤1,0002 \le N \le 1{,}000) barns, conveniently numbered 1…N1 \ldots N. Farmer John has already done some surveying and found MM (1≤M≤20,0001 \le M \le 20{,}000) possible connection routes between pairs of barns. Each possible connection route has an associated cost CC (1≤C≤100,0001 \le C \le 100{,}000). Farmer John wants to spend as little as possible on connecting the network; he does not even want to pay Bessie.

Realizing that Farmer John will not pay her, Bessie decides to do the worst job possible. She must choose a set of connections to install so that:

  1. the total cost of these connections is as large as possible;
  2. all the barns are connected together (it is possible to reach any barn from any other barn via a path of installed connections); and
  3. there are no cycles among the connections (which Farmer John would easily detect).

Conditions 2 and 3 ensure that the final set of connections forms a tree.

Input

  • Line 1: Two space-separated integers, NN and MM.
  • Lines 2…M+12 \ldots M+1: Each line contains three space-separated integers AA, BB, and CC, describing a connection route between barns AA and BB with cost CC.

Output

  • Line 1: A single integer: the largest possible total cost of a set of connections that forms a spanning tree of all the barns. If it is impossible to connect all the barns, output −1-1 instead.

Examples1

  1. Example 1

    Input
    5 8
    1 2 3
    1 3 7
    2 3 10
    2 4 4
    2 5 8
    3 4 6
    3 5 2
    4 5 17
    
    Expected output
    42