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.