Minimum Spanning Tree Test

View as PDF

Submit solution

Points: 7
Time limit: 2.0s
Java 8 3.0s
Memory limit: 64M

Author:
Problem type

A minimum spanning tree for an undirected graph is a subgraph that connects every single node in that graph such that the sum of the weights of all the edges in the subgraph are minimized. Given a connected graph, find the total cost of a minimum spanning tree for it.

Input Specification

The first line of input contains the integer n (1 \le n \le 10^5) representing the number of nodes in the graph. They are numbered 0 to n - 1
The second line is an integer m (n-1 \le m \le 5n) representing the number of edges in the graph.
The next m lines each contain three space separated integers representing an edge:

  • The first two integers m_1, m_2 (0 \le m_1, m_2 < n) show that there is an edge connecting m_1 and m_2.
  • The third integer is m_3 (0 \le |m_3| \le 1000) representing the cost of this edge.
  • It is possible that there will be multiple edges connecting the same two nodes.

Output Specification

Output a single integer representing the total cost of a minimum spanning tree for the provided graph.
Note: For Java, use of Scanner may cause passable solutions to TLE. Faster input reading is recommended.

Sample Input

7
10
0 1 11
6 4 8
4 0 1
0 3 -12
5 1 9
1 2 32
1 3 5
6 3 18
0 5 2
6 2 5

Sample Output

9

Explanation for Sample

The graph can be visualized as follows (one indexed):

graph

The edges in green represent edges that are part of a minimum spanning tree of the graph whose sum of costs is 9.


Comments

There are no comments at the moment.