A mountaineering expedition maintains a branching network of camps: one base camp at the root, and every other camp is supplied by exactly one camp above it, so the whole layout forms a tree. Each camp carries a numeric camp code used for its radio call sign. Before the climb, the expedition's logistics team must build a completely independent backup network with the exact same shape and the exact same camp codes, so that if the primary network's records are ever lost the backup can still be read out on its own. You are given the primary camp network; build the backup network from scratch (brand-new camp records, not references into the primary network) and report its layout by listing the camp codes of the backup network in pre-order: visit a camp, then recursively visit its supply camps from first to last, in exactly the order they were listed for the primary network.
n — the number of camps (1 <= n <= 10^4). Camps are numbered 1 to n, and camp 1 is always the base camp (the root).n integers — the camp code of camp 1, camp 2, ..., camp n, in order (each code satisfies -10^9 <= code <= 10^9).n - 1 lines each contain two integers p c, meaning camp c is directly supplied by camp p (camp c is a child of camp p). Among all lines naming the same parent p, the order those lines appear in the input is the left-to-right order of p's supply camps. The given edges are guaranteed to form a valid tree rooted at camp 1 (every camp other than camp 1 has exactly one parent, and there are no cycles).Print n integers separated by single spaces on one line: the camp codes of the backup network visited in pre-order, starting from the backup of camp 1 and recursing into its supply camps in the same left-to-right order given in the input.
n - 1 edges always form a valid tree rooted at camp 1.Example 1
Input
4 1 2 3 4 1 2 1 3 3 4
Expected
1 2 3 4
Explanation
Camp 1 (code 1) directly supplies camp 2 (code 2) and camp 3 (code 3), in that order; camp 3 in turn supplies camp 4 (code 4). Building the backup network and reading it in pre-order visits camp 1, then camp 2, then camp 3, then camp 4, giving codes `1 2 3 4`.
Example 2
Input
1 7
Expected
7
Explanation
There is only the base camp, with code 7 and no supply camps, so the backup network is a single camp with code 7 and the pre-order listing is just `7`.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →