Common Subexpression Elimination
Time limit1sMemory limit128 MB
Compress a labeled binary expression tree into a minimal DAG by merging identical subexpressions and print it with backreference numbers to earlier nodes.
Problem
Let the set consist of all words made of 1 to 4 lowercase letters, such as a, b, f, aa, fun, and kvqf. For any symbol , expressions are built with the two grammar rules
Every expression corresponds to a tree that mirrors its syntax. For example, the expression
a(b(f(a,a),b(f(a,a),f)),f(b(f(a,a),b(f(a,a),f)),f))
corresponds to a tree with nodes.
We can shrink this representation by using a graph (a directed acyclic graph) instead of a tree, so that identical subexpressions are stored once and shared. The expression above can be represented by such a graph with only nodes.
Because a tree is itself a graph, the graph representation is not unique. Given an expression, find a graph that represents it using as few nodes as possible.
Input
The first line contains an integer (), the number of expressions. Each of the next lines contains one expression written according to the grammar above, with no whitespace. The tree representation of each expression contains at most nodes.
Output
For each expression, print one line containing a graph representation that uses as few nodes as possible.
The graph representation is written as a string by replacing repeated subexpressions with numbers. Each number refers to the root node of the subexpression that must be inserted at that position. Nodes are numbered sequentially starting from , in the order they are first written down; this numbering counts only the nodes that actually appear in the graph, not the occurrences that were replaced by a number. A number may only refer to a node written down earlier, so there are no forward references.
For the example expression a(b(f(a,a),b(f(a,a),f)),f(b(f(a,a),b(f(a,a),f)),f)), the answer is a(b(f(a,4),b(3,f)),f(2,6)).