A network operator wants to connect n sites, numbered 0 to n - 1, using exactly
n - 1 of the m available candidate links so that every site is connected to every other site
(directly or indirectly), and no candidate link is redundant (the chosen set forms a tree). Candidate
link i connects sites u and v at a cost of w; multiple candidate links between the same pair of
sites may exist, each counted as a distinct link.
Among all such valid networks (spanning trees), the cheapest one has some minimum total cost. Print the
SECOND smallest DISTINCT total cost achievable by a valid network -- that is, the smallest total cost
that is strictly greater than the minimum. If the sites cannot all be connected at all, or if every
possible valid network has the exact same total cost (so no second, larger, distinct cost exists),
print -1 instead.
Line 1: two integers n m.
Next m lines: three integers u v w -- an undirected candidate link between sites u and v
costing w (sites are 0-indexed).
A single integer: the second-smallest distinct total cost among all valid spanning networks, or -1
if it does not exist.
Example 1
Input
3 3 0 1 1 1 2 2 0 2 5
Expected
6
Explanation
The cheapest network uses links 0-1 and 1-2 for a total of 3; the next-cheapest alternative swaps in link 0-2 to give 0-1 + 0-2 = 6, so the second-best total cost is 6.
Example 2
Input
3 2 0 1 1 1 2 2
Expected
-1
Explanation
With only two links and three sites, both links are required to connect everyone, so there is only one possible network and no second-best cost exists, giving -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →