#C2971. Mystical Forest Minimum Spanning Tree

    ID: 46346 Type: Default 1000ms 256MiB

Mystical Forest Minimum Spanning Tree

Mystical Forest Minimum Spanning Tree

In a dense mystical forest, trees are connected by magical paths. Each path is associated with a weight that represents the magical energy flowing between the trees. The forest can be modeled as an undirected graph with n nodes (trees) and m edges (paths). Your task is to determine the total weight of the Minimum Spanning Tree (MST) of this graph. If it is impossible to connect all trees (i.e. the graph is disconnected), print NO.

The MST is a subset of the edges that connects all the nodes together without forming any cycles and with the minimum possible total edge weight. Mathematically, if the forest is fully connected, the MST consists of n - 1 edges. Use the standard algorithms (such as Kruskal's or Prim's) to solve the problem.

Note: If a valid MST is not achievable (i.e., not enough edges to connect all trees), output NO.

inputFormat

The first line contains two integers n and m separated by a space, where n is the number of trees and m is the number of magical paths. The following m lines each contain three integers u, v, and w indicating that there is a path between tree u and tree v with weight w.

Example:
4 5
1 2 3
1 3 1
2 3 3
3 4 6
1 4 5

outputFormat

If a Minimum Spanning Tree exists, print its total weight. Otherwise, print NO.

Example Output:
9
## sample
4 5
1 2 3
1 3 1
2 3 3
3 4 6
1 4 5
9