#C4709. Minimal Communication Cost in Planetary Network

    ID: 48277 Type: Default 1000ms 256MiB

Minimal Communication Cost in Planetary Network

Minimal Communication Cost in Planetary Network

You are given a network of n planets connected by m bidirectional communication channels. Each communication channel connects two distinct planets and has an associated cost. The task is to determine the minimal total communication cost to connect all the planets.

This problem can be solved using a Minimum Spanning Tree (MST) algorithm – for example, Kruskal's algorithm. Formally, if the set of edges in the MST is \(E_{MST}\), then the total minimal cost is given by:

[ TotalCost = \sum_{(u,v,w) \in E_{MST}} w ]

If there is only one planet (i.e. \(n=1\)), then the total cost is 0. All input values are such that a spanning tree exists.

inputFormat

The input is given via stdin and has the following format:

n m
u1 v1 w1
...
um vm wm

Where:

  • n is the number of planets.
  • m is the number of communication channels.
  • Each of the next m lines contains three integers u, v, w representing a channel between planet u and planet v with cost w.

outputFormat

The output is a single integer printed to stdout representing the minimal total communication cost to connect all the planets.

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