#K44077. Minimum Communication Delay

    ID: 27451 Type: Default 1000ms 256MiB

Minimum Communication Delay

Minimum Communication Delay

You are given a network of n computers labeled from 1 to n and a list of m connections. Each connection is represented by three integers a, b and t where t denotes the communication delay between computers a and b.

Your task is to determine the minimum total communication delay required to connect all computers. In other words, find the minimum sum of delays such that every computer is connected directly or indirectly with each other. If it is impossible to connect all computers, output -1.

This problem can be modeled as finding a minimum spanning tree (MST) of a graph. Using Kruskal's algorithm with a union-find data structure is a typical approach.

The formula used in the solution is based on the MST concept: \( MST = \min \sum_{e \in T} t_e \) where \( T \) is a subset of edges that connects all vertices.

inputFormat

The first line contains two integers n and m separated by a space, where n is the number of computers and m is the number of connections.

Each of the following m lines contains three integers a, b and t representing a connection between computers a and b with a communication delay t.

outputFormat

Output a single integer which is the minimum total communication delay needed to connect all computers. If it is impossible to connect every computer, output -1.

## sample
4 4
1 2 1
2 3 2
3 4 1
1 4 4
4

</p>