#K92962. Minimum Cost to Connect All Computers

    ID: 38314 Type: Default 1000ms 256MiB

Minimum Cost to Connect All Computers

Minimum Cost to Connect All Computers

You are given a network of n computers (numbered from 1 to n) and a list of available bidirectional connections between them. Each connection has an associated cost. Your task is to compute the minimum total cost required to connect all the computers so that every computer can communicate with every other computer directly or indirectly.

If it is impossible to connect all the computers using the available connections, output -1.

This is a classic Minimum Spanning Tree problem which can be solved using algorithms such as Kruskal's algorithm with union-find (disjoint set union).

Note: The input is read from stdin and the output is written to stdout.

inputFormat

The first line of input contains two integers n and m, where n (1 ≤ n ≤ 105) is the number of computers and m is the number of connections available.

The following m lines each contain three integers u, v, and w representing a connection between computers u and v with cost w (1 ≤ w ≤ 106).

outputFormat

Output a single integer: the minimum total cost to connect all computers. If it's not possible to connect all computers, output -1.

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