Brackets
Time limit1sMemory limit128 MB
Count the ways to fully bracket a minus chain so that the result equals a target expression with given signs, modulo 1e9.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Combinatorics, Math
- Solved
- No attempts yet
Problem
Subtraction is not associative. For example , but , so . This means the value of an expression such as depends on the order in which the subtractions are carried out. When no brackets are written, the operations are performed from left to right, so means .
You are given an expression of the form
where each is either (plus) or (minus), and are pairwise distinct variables.
Into the all-minus expression
you want to insert brackets so that the result is equivalent to the given expression. For example, to obtain an expression equivalent to
you may bracket as
We consider only fully and correctly bracketed expressions. An expression is fully and correctly bracketed when it is:
- a single variable, or
- of the form , where and are themselves fully and correctly bracketed expressions.
Expressions with redundant brackets, such as , , or , are not allowed. The expression is not fully bracketed either, because it lacks the outermost brackets.
Write a program that reads the given expression and computes, modulo , the number of different ways to insert pairs of brackets into so that the order of the subtractions is fully determined and the resulting expression is equivalent to the given one.
Input
The first line contains one integer with , the number of variables. Each of the next lines contains a single character, or . The character on the -th of these lines is the operator between and in the given expression.
Output
Print a single integer: the number of different ways, modulo , to insert pairs of brackets into so that the order of the subtractions is fully determined and the resulting expression is equivalent to the given one.