Minimum Spanning Tree
Time limit1sMemory limit128 MB
Given a weighted graph and several spanning trees written as nested lists, decide for each whether it is a minimum spanning tree.
- Level
Medium7 of 10
- Topics
- Minimum spanning tree, Union-find, Sorting, Implementation
- Solved
- No attempts yet
Problem
is a connected, weighted, undirected graph. A spanning tree of is a subgraph that (1) is a tree and (2) connects all vertices of . The weight of a spanning tree is the sum of the weights of its edges. A minimum spanning tree is a spanning tree whose weight is less than or equal to the weight of every other spanning tree.
Write a program that determines whether a given tree is a minimum spanning tree of a given graph .
Input
The input consists of one or more test cases. Each test case gives a graph and one or more trees to test.
The first line of a test case contains a single integer (), the number of vertices of . Vertices are numbered from to .
The next lines give the upper triangle of the weighted adjacency matrix:
W(1,2) W(1,3) ... W(1,n-1) W(1,n)
W(2,3) W(2,4) ... W(2,n)
...
W(n-1,n)
where () is the weight of the edge between vertices and , and means there is no edge between them.
After the matrix, a line contains a single integer (), the number of trees to test on this graph.
Each of the next trees is either a single vertex, given by its number, or is written as
(R T1 T2 ... Tc)
where is the root vertex and () are its subtrees, described recursively in the same way.
The end of the input is a line containing a single in place of .
Output
For each tree, print one line of the form
a.b result
where is the test case number (starting at ), is the tree number within that test case (starting at ), and result is YES if the tree is a minimum spanning tree of and NO otherwise. Put a single space between and result, and leave no trailing spaces.