#K39472. Minimum Time to Connect All Grids

    ID: 26428 Type: Default 1000ms 256MiB

Minimum Time to Connect All Grids

Minimum Time to Connect All Grids

You are given a network of grids represented by nodes and connections between them represented by edges. Each edge has an associated time (or weight). Your task is to determine the minimum total time required to connect all the grids into a single connected network. In other words, you must find the weight sum of the Minimum Spanning Tree (MST) of the graph. If it is impossible to connect all grids (i.e. the graph is disconnected), output -1.

The mathematical formulation can be presented as follows:

$$\text{Minimum Time} = \min \sum_{e \in \text{MST}} w_e$$

where \(w_e\) is the weight of edge \(e\). ## inputFormat Input is received from standard input (stdin). The first line contains two integers \(N\) and \(M\), where \(N\) is the number of grids (nodes) and \(M\) is the number of connections (edges). The following \(M\) lines each contain three integers \(u\), \(v\) and \(w\), denoting an edge between grid \(u\) and grid \(v\) with connection time \(w\). Note that the grid numbering starts at 1. ## outputFormat Output a single integer to standard output (stdout) — the minimum total time required to connect all grids into a single connected network. If it is impossible to connect all grids, output -1.## sample
4 5
1 2 1
2 3 4
3 4 2
1 4 3
1 3 5
6
$$