Distance Code
Time limit1sMemory limit1024 MB
Write an encoder that orders the removal of tree leaves, and a decoder that rebuilds an isomorphic tree from the distances between successive removed nodes.
- Level
Hard8 of 10
- Topics
- Tree, Implementation, BFS
- Solved
- No attempts yet
Problem
Your task is to create a program that can be used in two ways: as an encoder and as a decoder.
The encoder is given a tree of nodes and removes all nodes from the tree. On each step, the encoder may remove any leaf from the current tree.
The decoder is given a list of distances between successively removed nodes by the encoder. It has to reconstruct the original structure of the tree. The decoder has to create a tree with the same structure as the original tree (more precisely, it has to be isomorphic to the original tree).
Input
The first line has an integer , which is either (encoder) or (decoder).
The second line has an integer , the number of nodes in the tree. The nodes are numbered .
If , there are then lines describing the tree. Each line has two integers and , meaning there is an edge between nodes and .
If , there is only one line with integers: the distances between successively removed nodes.
Output
If , the encoder has to print a permutation of the numbers : the order in which the nodes are removed from the tree.
If , the decoder has to print lines that describe the structure of the tree.