#P70. [CSP-S 2019 Day 1] Cut and Swap

[CSP-S 2019 Day 1] Cut and Swap

Person in Charge

Problem Description

Given a tree of size nn, it has nn nodes and n1n - 1 edges, with nodes numbered from 11 to nn. Initially, each node has a number from 11 to nn, and each number from 11 to nn appears on exactly one node.

Next, you need to perform exactly n1n - 1 edge deletion operations. In each operation, you select an edge that has not been deleted yet. At this time, the numbers on the two nodes connected by this edge will be swapped, and then the edge will be deleted.

After n1n - 1 operations, all edges will be deleted. At this point, arrange the node numbers where the numbers 1n1 \sim n are located in ascending order of the numbers to obtain a permutation PiP_i of node numbers. Now, please find the lexicographically smallest PiP_i that can be obtained under the optimal operation scheme.

As shown in the left figure, the numbers 151 \sim 5 in the blue circles are initially on nodes ②, ①, ③, ⑤, ④ respectively. Deleting all edges in the order of (1)(4)(3)(2), the tree becomes the right figure. The permutation of node numbers obtained in the order of the numbers is ①③④②⑤, which is the lexicographically smallest among all possible results.

(The following images are from LibreOJ)

Input Format

This input contains multiple test cases.

The first line contains a positive integer TT, representing the number of test cases.

For each test case:

  • The first line contains an integer nn, representing the size of the tree.
  • The second line contains nn integers, where the ii-th integer (1in1 \le i \le n) represents the node number where the number ii is initially located.
  • The next n1n - 1 lines each contain two integers xx and yy, representing an edge connecting node xx and node yy.

Output Format

For each test case, output a line with nn integers separated by spaces, representing the lexicographically smallest PiP_i obtainable under the optimal operation scheme.

Sample 1

See tree/tree1.in and tree/tree1.ans in the contestant's directory.

Sample 2

See tree/tree2.in and tree/tree2.ans in the contestant's directory.

Data Range

Test Case ID nn \le Special Property
121 \sim 2 1010 None
343 \sim 4 160160 The tree is a chain
575 \sim 7 20002000
898 \sim 9 160160 There exists a node with degree n1n - 1
101210 \sim 12 20002000
131613 \sim 16 160160 None
172017 \sim 20 20002000

For 100%100\% of the data: 1T101 \le T \le 10, 1n20001 \le n \le 2000, the given graph is a tree, and the initial nn numbers form a permutation of 1n1 \sim n.