Lengthy Traveling Salesman
Time limit1sMemory limit256 MB
Arrange every vertex of a tree into a tour that maximizes the total walked distance and return the lexicographically smallest among the longest tours.
Problem
Karel wants to register his robot for a robot contest. Registering takes a safety certificate for the robot and several forms. Karel starts at the entrance of the organizers' building, visits every office once in a prescribed order, and returns to the entrance. The hallways of the building contain no cycle, so exactly one path runs between any two offices.
Running a contest takes more than a problem statement and a model solution. The organizers also need test data that checks submitted programs, and rejecting inefficient programs takes the visiting order whose walk is as long as possible. Find that order.
The building is a tree with vertices and one office in every vertex. A tree is a set of vertices joined by edges. Each edge joins two vertices, and exactly one path runs between any two vertices and . The length of a path is the number of edges you traverse when you walk from to , written .
Input
The input holds several test cases. The first line of a test case holds the number of vertices of the tree, (). The vertices are numbered from to . The -th of the next lines holds an integer (), meaning that the tree has an edge between vertex and vertex .
One empty line follows each test case. The input ends at the end of the file. There are at most test cases, and the sum of over all test cases is at most .
Output
For each test case, print one line with integers separated by spaces. Each of must appear exactly once, and the sum
must be as large as possible.
Several permutations usually reach that maximum. Print only the lexicographically smallest one. Comparing two permutations from the front, the one holding the smaller number at the first position where they differ is the lexicographically smaller one.