#K16091. Minimum Spanning Tree Toll Fee

    ID: 24501 Type: Default 1000ms 256MiB

Minimum Spanning Tree Toll Fee

Minimum Spanning Tree Toll Fee

You are given a weighted undirected graph representing regions and roads connecting them. Each road has a toll fee. Your task is to compute the total toll fee of the minimum spanning tree (MST) using Kruskal's algorithm. In other words, you must select a subset of roads that connects all regions (or as many as possible if the graph is disconnected) with the minimum possible sum of toll fees.

The MST weight is given by the following formula:

\(\text{MST\_sum} = \sum_{e \in T} w_e\),

where \(T\) is the set of edges included in the MST, and \(w_e\) is the toll fee of edge \(e\).

If the graph is disconnected, compute the sum of toll fees of the minimum spanning forest (i.e. the sum of the MSTs of each connected component).

inputFormat

The input is given via standard input in the following format:

n m
u1 v1 w1
u2 v2 w2
... 
um v m w m

Where:

  • n is the number of regions,
  • m is the number of roads,
  • Each of the following m lines contains three integers u, v and w representing a road connecting regions u and v with a toll fee of w.

outputFormat

Output a single integer on standard output representing the total toll fee of the minimum spanning tree (MST) or the minimum spanning forest if the graph is disconnected.

## sample
4 5
1 2 1
1 3 4
2 3 2
3 4 3
4 1 5
6