Problem R
Common Subexpression Elimination
Let the set
for every symbol
![\includegraphics[width=0.8\textwidth ]{tree.png}](/problems/subexpression/file/statement/en/img-0001.png)
Last night you dreamt of a great invention which considerably reduces the size of the representation: use a graph instead of a tree, to share common subexpressions. For example, the expression above can be represented by the graph on the right in the figure. While the tree contains 21 nodes, the graph just contains 7 nodes.
Since the tree on the left in the figure is also a graph, the representation using graphs is not necessarily unique. Given an expression, find a graph representing the expression with as few nodes as possible!
Input
The first line of the input contains the number
Output
For each expression, print a single line containing a graph representation with as few nodes as possible.
The graph representation is written down as a string by
replacing the appropriate subexpressions with numbers. Each
number points to the root node of the subexpression which
should be inserted at that position. Nodes are numbered
sequentially, starting with 1; this numbering includes just the
nodes of the graph (not those which have been replaced by
numbers). Numbers must point to nodes written down before (no
forward pointers). For our example, we obtain
Sample Input 1 | Sample Output 1 |
---|---|
3 this(is(a,tiny),tree) a(b(f(a,a),b(f(a,a),f)),f(b(f(a,a),b(f(a,a),f)),f)) z(zz(zzzz(zz,z),zzzz(zz,z)),zzzz(zz(zzzz(zz,z),zzzz(zz,z)),z)) |
this(is(a,tiny),tree) a(b(f(a,4),b(3,f)),f(2,6)) z(zz(zzzz(zz,z),3),zzzz(2,5)) |