UVa 10454 - Trexpression

Summary
How many distinct ways an expression consisting of operands, operator '+', operator '*' and parenthesis, can be correctly evaluated.

Explanation
Let $$E(n)$$ be an expression with expressions as the operands $$x_i,\ 1\le i\le n$$ and only one kind of operator (with loss of generality, the plus operator will be used): $$ E(n) = x_1 + x_2 + x_3 + ... + x_n $$

Let $$f(n)$$ be the number of ways an expression $$E(n)$$ can be evaluated.

The answer for an expression with only one operand and no operators is trivial: $$f(0) = 1$$

To evaluate $$E(n),\ n > 0$$, one can choose any of the $$n$$ operators to be the last one to be evaluated. If one choose the $$i-th$$ operator, there will be $$f(i-1) * f(n-i)$$.

Therefore, $$f(n) = \sum_{i = 1}^{n}f(i-1)*f(n-i)$$.

As you may be familiar with, this is the famous Catalan number.

Extending this idea for general expression with sub-expressions, it's easy to see that the recursive Catalan idea maintains, only being multiplied by the answers of the sub-expressions. It only rests parse the input expression to oblige the precedence constraints and multiply for each "level" the Catalan number corresponding to the number of operands in the expression and the answers of the sub-expressions.

Optimizations
Pre calculate Catalan numbers.

Input
1+2+3+4 (1+2)+(3+4) 1+2+3*4 1+2+(3*4)

Output
5 1 2 2