#K37237. Connecting Warehouse Sections

    ID: 25932 Type: Default 1000ms 256MiB

Connecting Warehouse Sections

Connecting Warehouse Sections

You are given a warehouse with n sections and m potential direct connections. Each direct connection connects two sections and has an associated cost.

Your task is to determine the minimum cost required to connect all sections, i.e. to form a Minimum Spanning Tree (MST). If it is impossible to connect all the sections, output -1.

The minimum cost is computed as the sum of the weights of the connections selected. In mathematical terms, if the set of selected connections (edges) is MST, then the cost is given by:

\(\text{Cost} = \sum_{e \in MST} w_e\)

The problem may contain multiple test cases.

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains a single integer T representing the number of test cases.
  • Each test case begins with a line containing two integers n (number of sections) and m (number of connections).
  • This is followed by m lines each containing three integers: u, v, and w, where u and v are the one-indexed identifiers of the sections and w is the cost of the direct connection between them.

outputFormat

For each test case, output a single line on standard output (stdout) with the minimum cost to connect all the sections. If it is impossible to connect all sections, output -1.

## sample
2
4 5
1 2 1
1 3 2
1 4 4
2 3 3
3 4 1
3 3
1 2 5
1 3 10
2 3 4
4

9

</p>