This page is still under construction.

Parts of this page are still being built. What you see may change.

Untamed Tree

Time limit1sMemory limit128 MB

Summary
The task is to output for each leaf label the compressed subtree of its leaves and branching ancestors in preorder.
Level

Hard8 of 10

Topics
Tree, Sorting, Stack, Hash map
Solved
No attempts yet

Problem

You are given a rooted binary tree TT. Every internal vertex of TT 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 ℓ\ell, the tree T(ℓ)T(\ell) is defined as follows:

  • The leaves of T(ℓ)T(\ell) are exactly the leaves of TT whose label is ℓ\ell.
  • T(ℓ)T(\ell) also contains every internal vertex of TT whose left subtree and right subtree both contain at least one leaf labelled ℓ\ell.
  • Two vertices uu and vv kept in T(ℓ)T(\ell) are joined by an edge when the path between them in TT passes through no other kept vertex.

Write a program that, for every label appearing in TT, determines the tree T(ℓ)T(\ell).

Input

Each line of standard input describes exactly one vertex of TT. 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 1 000 0001\,000\,000 (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 11; that is, a vertex's number equals its line number.

Output

Print the description of every tree T(ℓ)T(\ell), one per line, with the labels ℓ\ell 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.

Examples3

  1. Example 1

    Input
    *
    *
    a
    ab
    *
    *
    c
    ab
    *
    c
    c
    
    Expected output
    3
    1 4 8
    5 7 9 10 11
    
  2. Example 2

    Input
    a
    
    Expected output
    1
    
  3. Example 3

    Input
    *
    x
    x
    
    Expected output
    1 2 3