#P5659. [CSP-S 2019] 树上的数

[CSP-S 2019] 树上的数

Problem Description

Given a tree of size nn, it has nn nodes and n1n - 1 edges, with nodes numbered from 1n1 \sim n. Initially, each node contains a number from 1n1 \sim n, and each number from 1n1 \sim n appears on exactly one node.

Next, you need to perform exactly n1n - 1 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 n1n - 1 operations, all edges will have been deleted. At this time, list the node indices where numbers 1n1 \sim n are located in increasing order of the numbers, and you obtain a permutation of node indices PiP_i. Now, please find the lexicographically smallest PiP_i that can be obtained under an optimal sequence of operations.

As shown above, the numbers 151 \sim 5 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 TT, indicating the number of test cases.

For each test case:

The first line contains an integer nn, indicating the size of the tree.

The second line contains nn integers. The i(1in)i (1 \leq i \leq n)-th integer indicates the node index where number ii is initially located.

The next n1n - 1 lines each contain two integers xx, yy, indicating an edge connecting node xx and node yy.

Output Format

For each test case, output one line with nn integers separated by spaces, representing the lexicographically smallest PiP_i 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 nn \leq Special Property
121 \sim 2 1010 None
343 \sim 4 160160 The tree is a chain
575 \sim 7 20002000 Same as above
898 \sim 9 160160 There exists a node with degree n1n - 1
101210 \sim 12 20002000 Same as above
131613 \sim 16 160160 None
172017 \sim 20 20002000

For all test points: 1T101 \leq T \leq 10, and it is guaranteed that the input is a tree.

Translated by ChatGPT 5