#CSPS2019C. 树上的数 (Numbers on the Tree)
树上的数 (Numbers on the Tree)
Description
You are given a tree consisting of nodes numbered from and edges. Initially, each node has a label assigned to it from , and each label from is assigned to exactly one node.
You need to perform exactly edge deletion operations. In each operation, you need to select an edge that has not been deleted. Then, the labels assigned to the two nodes connected by this edge are swapped, and this edge is deleted.
After operations, all edges will be deleted. Now, the nodes are arranged according to increasing order of the labels to obtain a sequence of nodes . Find the lexicographically smallest sequence that can be obtained by applying the operations in an optimal order.
As shown in the figure on the left, initially, the numbers in the blue circles are the labels of nodes ②, ①, ③, ⑤, ④ respectively. The edges are deleted in the order (1)(4)(3)(2), which changes the tree to the figure on the right. The nodes are arranged by increasing order of their labels to obtain the sequence ①③④②⑤, which is the lexicographically smallest sequence among all possible results.
Input Format
The input contains multiple test cases.
The first line contains a positive integer denoting the number of test cases.
For each test case:
The first line contains an integer denoting the number of nodes in the tree.
The second line contains integers where the -th integer () denotes the node which has label initially.
Each of the next lines contains two integers and denoting there's an edge between node and node .
Output Format
For each test case, print one line containing space-separated integers denoting the lexicographically smallest sequence that can be obtained by applying the operations in an optimal order.
4
5
2 1 3 5 4
1 3
1 4
2 4
4 5
5
3 4 2 1 5
1 2
2 3
3 4
4 5
5
1 2 5 3 4
1 2
1 3
1 4
1 5
10
1 2 3 4 5 7 8 9 10 6
1 2
1 3
1 4
1 5
5 6
6 7
7 8
8 9
9 10
1 3 4 2 5
1 3 5 2 4
2 3 1 4 5
2 3 4 5 6 1 7 8 9 10
Sample 2
See the additional files tree2.in and tree2.ans for details.
Constraints
Tests | Special nature | |
---|---|---|
None | ||
The tree is a chain | ||
There exists a node of degree | ||
None | ||
For all the tests: , and it is guaranteed that the given edges form a tree.