Untamed Tree
Time limit1sMemory limit128 MB
The task is to output for each leaf label the compressed subtree of its leaves and branching ancestors in preorder.
Problem
You are given a rooted binary tree . Every internal vertex of has exactly two children, a left child and a right child, and every leaf carries a label. A label is a non-empty string of lowercase English letters, and different leaves may carry the same label.
For a label , the tree is defined as follows:
- The leaves of are exactly the leaves of whose label is .
- also contains every internal vertex of whose left subtree and right subtree both contain at least one leaf labelled .
- Two vertices and kept in are joined by an edge when the path between them in passes through no other kept vertex.
Write a program that, for every label appearing in , determines the tree .
Input
Each line of standard input describes exactly one vertex of . The tree is given in pre-order: the first line of every (sub)tree describes its root, and if that root is an internal vertex, the description of its left subtree follows and then the description of its right subtree. A line containing a single asterisk * denotes an internal vertex. A line containing a lowercase string denotes a leaf and gives its label; the label is non-empty and consists only of the letters a to z. The total length of all labels does not exceed (a label is counted once for every leaf where it occurs).
Vertices are numbered by the order in which they appear in the input, starting from ; that is, a vertex's number equals its line number.
Output
Print the description of every tree , one per line, with the labels taken in lexicographic order. Each description is written in pre-order but uses the numbers of the vertices belonging to the tree: the number of the root, followed (unless the root is a leaf) by the description of its left subtree and then of its right subtree.