Tree Generators
Time limit2sMemory limit2048 MB
Given two expressions that build trees by joining subtrees with a random edge, count the distinct trees both expressions can generate, modulo 998244353.
- Level
Hard9 of 10
- Topics
- Tree, Dynamic programming, Hash map
- Solved
- No attempts yet
Problem
Two expressions are given as input. Each one describes a procedure that generates a single tree. The procedure is randomized, so different trees may be generated each time it runs. Count the number of trees that can be generated from both expressions.
The syntax of an expression is as follows.
::= ‘1’ | ‘(’ ‘)’
A tree is generated from an expression as follows.
- The expression
1generates a tree with a single vertex labeled . - For two expressions and , the expression
()generates a tree as follows.- Generate a tree from with vertices, and a tree from with vertices.
- Increment the labels of all vertices in by .
- Choose one vertex from and one vertex from at random. Adding an edge between them forms a single tree with vertices labeled through . This is the tree generated by
().
For example, the expression (11) can generate only the leftmost tree in Figure D.1. The expression (1(11)) can generate the other two trees.

Figure D.1. Trees generated from the two expressions, (11) and (1(11))
The same tree can be generated from different expressions. The middle tree can also be generated from ((11)1).
For two expressions of the same length, count the trees that can be generated from both. The trees generated from the two expressions always have the same number of vertices. Two trees are different if there are two indices and such that vertices and are connected by an edge in one tree but not in the other.
Input
The input consists of two lines. Each line contains one expression string. The two strings have the same length, between and , inclusive. Both strings follow the syntax given above.
Output
Print the number of trees that can be generated from both expressions, modulo .
Hint
For Sample Input 1, the trees that can be generated from the two expressions are shown in Figure D.2. The top six trees come from the first expression, and the bottom four come from the second. Only the leftmost tree in each row can be generated from both.

Figure D.2. Illustration of Sample Input 1