Under construction

Still being built. Things may change

Expression Mining

Time limit2sMemory limit512 MB

Summary
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 EE, 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 nn and a string ss that represents an arithmetic expression, count the substrings of ss that can be read as arithmetic expressions whose computed value is nn.

Input

The input has multiple datasets, each in the following format.

The first line contains the target value nn, where 1≤n≤1091 \le n \le 10^9. The second line contains the string ss, an arithmetic expression that follows the grammar above. The length of ss is at most 2×1062 \times 10^6, and the nesting depth of parentheses in ss is at most 1000. The input ends with a line containing a single 0. The sum of the lengths of ss over all datasets is at most 5×1065 \times 10^6.

Output

For each dataset, output on one line the number of substrings of ss that conform to the grammar and have value nn. Identical substrings at different positions are counted separately.

Examples1

  1. Example 1

    Input
    3
    (1+2)*3+3
    2
    1*1*1+1*1*1
    587
    1*(2*3*4)+5+((6+7*8))*(9)
    0
    
    Expected output
    4
    9
    2