Cracking Tree Codes
InterviewTime limit1sMemory limit128 MB
Given a tree and its leaf-stripping code with some entries erased, the program replays the encoding to recover the missing numbers.
- Level
Easy3 of 10
- Topics
- Simulation, Tree, Heap
- Solved
- No attempts yet
Problem
Let and . A tree is a graph that is connected and has exactly edges. The figure below shows a tree .

In we have and .
Professor Minton found a way to encrypt a tree. The code of a tree is a sequence of numbers from , built by repeating these three steps times.
- In the part of the tree that is left, take the leaf (a vertex of degree ) with the smallest number.
- Append the number of the only vertex adjacent to that leaf to the sequence.
- Delete that leaf from the tree.
After rounds two vertices remain. The code of is .
A code sometimes arrives with a few of its numbers erased. Every erased position is written as the letter x. Given a tree and a code with erased numbers, write a program that recovers the erased numbers.
Input
The first line contains the number of test cases . ()
Each test case takes three lines. The first line contains the number of vertices . () The second line contains numbers separated by blanks that describe the tree. Reading two numbers at a time, the first pair is the first edge, the second pair is the second edge, and so on. The third line contains the code with erased numbers as tokens. Each token is either a vertex number or the letter x for an erased position. When the third line is empty.
The numbers that were not erased agree with the code of the given tree. The sum of over all test cases is at most .
Output
For each test case print one line holding the erased numbers in the order they appear in the input, separated by single blanks. If nothing was erased, print an empty line.