MST
View as PDF
Submit solution
Points:
100
Time limit:
1.0s
PyPy 3
3.0s
Python 3
3.0s
Memory limit:
500M
Problem type
You are given an undirected weighted graph. Compute the total weight of a Minimum Spanning Tree (MST) of the graph.
If the graph is disconnected, it has no spanning tree; in that case output
-1.
Input
The first line contains integers and
, the number of nodes and edges.
The following lines each contain three integers
,
, and
,
describing an undirected edge between
and
with weight
.
Nodes are numbered from to
.
Output
Output a single integer: the weight of an MST, or -1 if none exists.
Constraints
Example 1
Input
3 4
1 2 5
1 3 6
2 3 2
2 1 3
Output
5
Explanation
One MST uses edges of weights and
, for a total of
.
Example 2
Input
4 2
1 2 1
3 4 1
Output
-1
Comments