#P5659. [CSP-S 2019] 树上的数
[CSP-S 2019] 树上的数
Problem Description
Given a tree of size , it has nodes and edges, with nodes numbered from . Initially, each node contains a number from , and each number from appears on exactly one node.
Next, you need to perform exactly edge-deletion operations. In each operation, you choose an edge that has not been deleted. The numbers on the two endpoints of this edge will swap, and then this edge will be deleted.
After operations, all edges will have been deleted. At this time, list the node indices where numbers are located in increasing order of the numbers, and you obtain a permutation of node indices . Now, please find the lexicographically smallest that can be obtained under an optimal sequence of operations.

As shown above, the numbers in the blue circles are initially on nodes ②, ①, ③, ⑤, ④ respectively. Delete all edges in the order (1)(4)(3)(2), and the tree becomes the figure below. The node index permutation obtained by the number order is ①③④②⑤, which is the lexicographically smallest among all possible results.

Input Format
This problem contains multiple test cases.
The first line contains a positive integer , indicating the number of test cases.
For each test case:
The first line contains an integer , indicating the size of the tree.
The second line contains integers. The -th integer indicates the node index where number is initially located.
The next lines each contain two integers , , indicating an edge connecting node and node .
Output Format
For each test case, output one line with integers separated by spaces, representing the lexicographically smallest that can be obtained under an optimal sequence of operations.
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
Hint
Constraints
| Test Point ID | Special Property | |
|---|---|---|
| None | ||
| The tree is a chain | ||
| Same as above | ||
| There exists a node with degree | ||
| Same as above | ||
| None | ||
For all test points: , and it is guaranteed that the input is a tree.
Translated by ChatGPT 5