Expression Mining
Time limit2sMemory limit512 MB
Count the substrings of a given expression string that follow the grammar and evaluate to a target value n.
- Level
Medium7 of 10
- Topics
- Stack, Dynamic programming, Hash map
- Solved
- No attempts yet
Problem
Consider an arithmetic expression with start symbol , defined by the following grammar. It is built from single-digit positive integers, the addition symbol +, the multiplication symbol *, and parentheses ( and ).
E ::= T | E '+' T
T ::= F | T '*' F
F ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '(' E ')'
When such an expression is viewed as a string, a substring (a contiguous sequence of characters) may again form an arithmetic expression. Given an integer and a string that represents an arithmetic expression, count the substrings of that can be read as arithmetic expressions whose computed value is .
Input
The input has multiple datasets, each in the following format.
The first line contains the target value , where . The second line contains the string , an arithmetic expression that follows the grammar above. The length of is at most , and the nesting depth of parentheses in is at most 1000. The input ends with a line containing a single 0. The sum of the lengths of over all datasets is at most .
Output
For each dataset, output on one line the number of substrings of that conform to the grammar and have value . Identical substrings at different positions are counted separately.