problems / 191

Suki's Park Footpaths

medium graphs minimum-spanning-tree greedy sorting union-find 2000 ms · 256 MB

Suki's Park Footpaths

Suki loves exploring all the dog parks in her neighborhood. She's discovered n parks scattered around the area, and she knows the distances between each pair of parks. To make her explorations more convenient, she wants to connect all the parks with footpaths—but she wants to minimize the total length of footpaths built.

Being a resourceful dog, Suki knows that as long as every park is reachable from every other park (directly or through other parks), she can explore them all. She just needs to find the minimum total length of footpaths required to connect them all together.

Given n parks and the distances between pairs of parks, find the minimum total length of footpaths needed to connect all parks.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5), where n is the number of parks and m is the number of possible footpath connections.

The next m lines each contain three integers u, v, and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 10^9), representing a possible footpath from park u to park v with length w.

Output

Print the minimum total length of footpaths needed to connect all n parks. If it's impossible to connect all parks (the graph is not connected), print -1.

Notes

All parks must be reachable from each other. This is a minimum spanning tree problem.

Example 1

Input

3 3
1 2 1
2 3 2
1 3 4

Output

3

Example 2

Input

4 2
1 2 5
3 4 3

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

If a set of footpaths contains a loop, can you drop one of its paths and stay connected? Which path would you drop, and what does that say about the cheapest connecting set?

Hint 2

Process the footpaths from cheapest to most expensive, keeping one whenever it joins two parks that are not yet connected. A union-find structure can track which parks are already connected.

Hint 3

If the parks cannot all be joined, the answer is -1. A single park needs no footpaths at all, so check how many footpaths you kept at the end.

report an issue Prefer your own editor? sooks prep 191 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.