Bad Cowtractors
InterviewTime limit1sMemory limit128 MB
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 () barns, conveniently numbered . Farmer John has already done some surveying and found () possible connection routes between pairs of barns. Each possible connection route has an associated cost (). 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:
- the total cost of these connections is as large as possible;
- all the barns are connected together (it is possible to reach any barn from any other barn via a path of installed connections); and
- 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, and .
- Lines : Each line contains three space-separated integers , , and , describing a connection route between barns and with cost .
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 instead.