Problem:
Expression Mining
Consider an arithmetic expression built by combining single-digit positive integers
with addition symbols
+
, multiplication symbols
*
,
and parentheses
(
)
,
defined by the following grammar rules with the start symbol
E
.
E ::= T | E '+' T
  T ::= F | T '*' F
  F ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '(' E ')'
When such an arithmetic expression is viewed as a string,
its substring, that is, a contiguous sequence of characters within the string,
may again form an arithmetic expression.

Given an integer
n
and a string
s
representing an arithmetic expression,
let us count the number of its substrings that can be read as arithmetic expressions
with values computed equal to
n
.
Input
The input consists of multiple datasets, each in the following format.
n
s
A dataset consists of two lines.
In the first line, the target value
n
is given.
n
is an integer satisfying 1 ≤
n
≤ 10
9
.

The string
s
given in the second line
is an arithmetic expression conforming to the grammar defined above.
The length of
s
does not exceed 2×10
6
.
The nesting depth of the parentheses in the string is at most 1000.
The end of the input is indicated by a line containing a single zero.
The sum of the lengths of
s
in all the datasets does not exceed 5×10
6
.
Output
For each dataset, output in one line the number of substrings of
s
that
conform to the above grammar and have the value
n
.
The same sequence of characters appearing at different positions should be counted separately.
Sample Input
3
(1+2)*3+3
2
1*1*1+1*1*1
587
1*(2*3*4)+5+((6+7*8))*(9)
0
Output for the Sample Input
4
9
2

Submitted solutions:

code_snippet: // C++ includes used for precompiling -*- C++ -*-
// Copyright (C) 2003-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://w...content-available-to-author-only...u.org/licenses/>.
/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */
// 17.4.1.2 Headers
// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>

#endif
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T &a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T &a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline void compress(vector<T> &a) {
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
}
template <class T>
T rand(T l, T r) {
    static mt19937 mt(random_device{}());
    // [l, r)
    if constexpr (is_integral_v<T>) {
        return uniform_int_distribution<T>(l, r - 1)(mt);
    } else if constexpr (is_floating_point_v<T>) {
        return uniform_real_distribution<T>(l, r)(mt);
    }
}
constexpr int INF = 1001001001;
constexpr ll llINF = 3000000000000000010;
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint &operator+=(const modint &p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator-=(const modint &p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator*=(const modint &p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint &operator/=(const modint &p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint &p) const { return modint(*this) += p; }
    modint operator-(const modint &p) const { return modint(*this) -= p; }
    modint operator*(const modint &p) const { return modint(*this) *= p; }
    modint operator/(const modint &p) const { return modint(*this) /= p; }
    bool operator==(const modint &p) const { return x == p.x; }
    bool operator!=(const modint &p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream &operator<<(ostream &os, const modint &p) { return os << p.x; }
    friend istream &operator>>(istream &is, modint &a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
ll extgcd(ll a, ll b, ll &x, ll &y) {
    // ax+by=gcd(|a|,|b|)
    if (a < 0 || b < 0) {
        ll d = extgcd(abs(a), abs(b), x, y);
        if (a < 0) x = -x;
        if (b < 0) y = -y;
        return d;
    }
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
template <class T>
vector<T> dijkstra(vector<vector<pair<int, T>>> &g, vector<int> start) {
    using P = pair<T, int>;
    vector<T> dp(g.size(), numeric_limits<T>::max());
    priority_queue<P, vector<P>, greater<P>> que;
    for (int s : start) {
        dp[s] = 0;
        que.push({0, s});
    }
    while (que.size()) {
        auto [d, v] = que.top();
        que.pop();
        if (dp[v] != d) continue;
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], d + c)) que.push({dp[u], u});
        }
    }
    return dp;
}

vector<int> BFS01(vector<vector<pair<int, int>>> &g, vector<int> start) {
    vector<int> dp(g.size(), numeric_limits<int>::max());
    deque<int> que;
    for (int s : start) {
        dp[s] = 0;
        que.push_front(s);
    }
    while (que.size()) {
        auto v = que.front();
        que.pop_front();
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], dp[v] + c)) {
                if (c == 0)
                    que.push_front(u);
                else
                    que.push_back(u);
            }
        }
    }
    return dp;
}
template <typename T, typename U>
inline istream &operator>>(istream &is, pair<T, U> &rhs) {
    return is >> rhs.first >> rhs.second;
}
template <typename T>
inline istream &operator>>(istream &is, vector<T> &v) {
    for (auto &e : v) is >> e;
    return is;
}
template <typename T, typename U>
inline ostream &operator<<(ostream &os, const pair<T, U> &rhs) {
    return os << rhs.first << " " << rhs.second;
}
template <typename T>
inline ostream &operator<<(ostream &os, const vector<T> &v) {
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr;) {
        os << *itr;
        if (++itr != end_itr) os << " ";
    }
    return os;
}

struct UnionFind {
    vector<int> par, siz;
    UnionFind(int x) {
        par.resize(x);
        siz.resize(x);
        for (int i = 0; i < x; i++) {
            par[i] = i;
            siz[i] = 1;
        }
    }
    int find(int x) {
        if (par[x] == x) return x;
        return par[x] = find(par[x]);
    }
    bool unite(int x, int y) {
        x = find(x), y = find(y);
        if (x == y) return false;
        if (siz[x] < siz[y]) swap(x, y);
        par[y] = x;
        siz[x] += siz[y];

        return true;
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return siz[find(x)]; }
};
template <class T>
struct BIT {
    // 1-indexed
    int n, beki = 1;
    vector<T> bit;
    BIT(int x) {
        bit.resize(x + 1, 0);
        n = x;
        while (beki * 2 <= n) beki *= 2;
    }
    T sum(int i) {
        T res = 0;
        while (i > 0) {
            res += bit[i];
            i -= i & -i;
        }
        return res;
    }
    T sum(int l, int r) {
        //[l,r]
        return sum(r) - (l == 0 ? 0 : sum(l - 1));
    }
    void add(int i, T x) {
        while (i <= n) {
            bit[i] += x;
            i += i & -i;
        }
    }
    int lowerbound(T w) {
        if (w <= 0) return 0;
        int x = 0;
        for (int k = beki; k > 0; k >>= 1) {
            if (x + k <= n && bit[x + k] < w) {
                w -= bit[x + k];
                x += k;
            }
        }
        return x + 1;
    }
};
using mint = modint<998244353>;
ll calc(ll n, string s) {
    auto it = s.begin();
    ll ans = 0;
    function<ll()> rec = [&]() {
        // return evaluate value
        vector<int> vec{-2};
        while (it != s.end() && *it != ')') {
            if (*it == '+') {
                vec.push_back(-1);
                it++;
            } else if (*it == '*') {
                vec.push_back(-2);
                it++;
            } else if (isdigit(*it)) {
                vec.push_back(*it - '0');
                it++;
            } else if (*it == '(') {
                it++;
                vec.push_back(rec());
                it++;
            } else
                assert(false);
        }
        ll sum = 0;  //<=n
        deque<vector<ll>> deq;
        ll prod = 1, eval = 0;
        vector<ll> cur;
        deque<ll> in_T;
        ll prod2 = 1;
        int len = 0;
        for (int i = 0; i < vec.size(); i += 2) {
            len++;
            if (vec[i] == -1) {
                eval += prod;
                sum += prod;
                for (int j = cur.size() - 2; j >= 0; j--) {
                    cur[j] = min((ll)INF, cur[j] * cur[j + 1]);
                }
                reverse(all(cur));
                deq.push_back(cur);
                cur.clear();
                in_T.clear();
                prod2 = vec[i + 1];
                prod = vec[i + 1];
                cur.push_back(vec[i + 1]);
                in_T.push_back(vec[i + 1]);
            } else {
                prod = min((ll)INF, prod * vec[i + 1]);
                prod2 = prod2 * vec[i + 1];
                cur.push_back(vec[i + 1]);
                in_T.push_back(vec[i + 1]);
            }
            while (deq.size() && prod + sum > n) {
                sum -= deq.front().back();
                deq.front().pop_back();
                if (deq.front().empty())
                    deq.pop_front();
                else
                    sum += deq.front().back();
                len--;
            }
            // cout<<prod2<<endl;
            while (prod2 > n && in_T.size()) {
                prod2 /= in_T.front();
                in_T.pop_front();
            }
            if (deq.size())
                ans += len;
            else
                ans += in_T.size();
        }
        eval = min((ll)INF, eval + prod);
        // cout<<vec<<endl;
        // cout<<eval<<endl;
        return min((ll)INF, eval);
    };
    rec();
    return ans;
}

void solve() {
    int n;
    cin >> n;
    if (n == 0) exit(0);
    string s;
    cin >> s;
    // cerr<<calc(n,s)<<" "<<calc(n-1,s)<<endl;
    cout << calc(n, s) - calc(n - 1, s) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t = 1;
    // cin >> t;
    while (1) solve();
}
accuracy: 1
time_ms: 220
memory_kb: 74604
final_rank: 8

code_snippet: // C++ includes used for precompiling -*- C++ -*-
// Copyright (C) 2003-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://w...content-available-to-author-only...u.org/licenses/>.
/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */
// 17.4.1.2 Headers
// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>

#endif
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T &a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T &a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline void compress(vector<T> &a) {
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
}
template <class T>
T rand(T l, T r) {
    static mt19937 mt(random_device{}());
    // [l, r)
    if constexpr (is_integral_v<T>) {
        return uniform_int_distribution<T>(l, r - 1)(mt);
    } else if constexpr (is_floating_point_v<T>) {
        return uniform_real_distribution<T>(l, r)(mt);
    }
}
constexpr int INF = 1001001001;
constexpr ll llINF = 3000000000000000010;
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint &operator+=(const modint &p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator-=(const modint &p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator*=(const modint &p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint &operator/=(const modint &p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint &p) const { return modint(*this) += p; }
    modint operator-(const modint &p) const { return modint(*this) -= p; }
    modint operator*(const modint &p) const { return modint(*this) *= p; }
    modint operator/(const modint &p) const { return modint(*this) /= p; }
    bool operator==(const modint &p) const { return x == p.x; }
    bool operator!=(const modint &p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream &operator<<(ostream &os, const modint &p) { return os << p.x; }
    friend istream &operator>>(istream &is, modint &a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
ll extgcd(ll a, ll b, ll &x, ll &y) {
    // ax+by=gcd(|a|,|b|)
    if (a < 0 || b < 0) {
        ll d = extgcd(abs(a), abs(b), x, y);
        if (a < 0) x = -x;
        if (b < 0) y = -y;
        return d;
    }
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
template <class T>
vector<T> dijkstra(vector<vector<pair<int, T>>> &g, vector<int> start) {
    using P = pair<T, int>;
    vector<T> dp(g.size(), numeric_limits<T>::max());
    priority_queue<P, vector<P>, greater<P>> que;
    for (int s : start) {
        dp[s] = 0;
        que.push({0, s});
    }
    while (que.size()) {
        auto [d, v] = que.top();
        que.pop();
        if (dp[v] != d) continue;
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], d + c)) que.push({dp[u], u});
        }
    }
    return dp;
}

vector<int> BFS01(vector<vector<pair<int, int>>> &g, vector<int> start) {
    vector<int> dp(g.size(), numeric_limits<int>::max());
    deque<int> que;
    for (int s : start) {
        dp[s] = 0;
        que.push_front(s);
    }
    while (que.size()) {
        auto v = que.front();
        que.pop_front();
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], dp[v] + c)) {
                if (c == 0)
                    que.push_front(u);
                else
                    que.push_back(u);
            }
        }
    }
    return dp;
}
template <typename T, typename U>
inline istream &operator>>(istream &is, pair<T, U> &rhs) {
    return is >> rhs.first >> rhs.second;
}
template <typename T>
inline istream &operator>>(istream &is, vector<T> &v) {
    for (auto &e : v) is >> e;
    return is;
}
template <typename T, typename U>
inline ostream &operator<<(ostream &os, const pair<T, U> &rhs) {
    return os << rhs.first << " " << rhs.second;
}
template <typename T>
inline ostream &operator<<(ostream &os, const vector<T> &v) {
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr;) {
        os << *itr;
        if (++itr != end_itr) os << " ";
    }
    return os;
}

struct UnionFind {
    vector<int> par, siz;
    UnionFind(int x) {
        par.resize(x);
        siz.resize(x);
        for (int i = 0; i < x; i++) {
            par[i] = i;
            siz[i] = 1;
        }
    }
    int find(int x) {
        if (par[x] == x) return x;
        return par[x] = find(par[x]);
    }
    bool unite(int x, int y) {
        x = find(x), y = find(y);
        if (x == y) return false;
        if (siz[x] < siz[y]) swap(x, y);
        par[y] = x;
        siz[x] += siz[y];

        return true;
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return siz[find(x)]; }
};
template <class T>
struct BIT {
    // 1-indexed
    int n, beki = 1;
    vector<T> bit;
    BIT(int x) {
        bit.resize(x + 1, 0);
        n = x;
        while (beki * 2 <= n) beki *= 2;
    }
    T sum(int i) {
        T res = 0;
        while (i > 0) {
            res += bit[i];
            i -= i & -i;
        }
        return res;
    }
    T sum(int l, int r) {
        //[l,r]
        return sum(r) - (l == 0 ? 0 : sum(l - 1));
    }
    void add(int i, T x) {
        while (i <= n) {
            bit[i] += x;
            i += i & -i;
        }
    }
    int lowerbound(T w) {
        if (w <= 0) return 0;
        int x = 0;
        for (int k = beki; k > 0; k >>= 1) {
            if (x + k <= n && bit[x + k] < w) {
                w -= bit[x + k];
                x += k;
            }
        }
        return x + 1;
    }
};
using mint = modint<998244353>;
using State = string::iterator;
using F = pair<ll, ll>;
ll calc(ll n, string s) {
    auto it = s.begin();
    ll ans = 0;
    function<ll()> rec = [&]() {
        // return evaluate value
        vector<int> vec{-2};
        while (it != s.end() && *it != ')') {
            if (*it == '+') {
                vec.push_back(-1);
                it++;
            } else if (*it == '*') {
                vec.push_back(-2);
                it++;
            } else if (isdigit(*it)) {
                vec.push_back(*it - '0');
                it++;
            } else if (*it == '(') {
                it++;
                vec.push_back(rec());
                it++;
            } else
                assert(false);
        }
        ll sum = 0;  //<=n
        deque<vector<ll>> deq;
        ll prod = 1, eval = 0;
        vector<ll> cur;
        deque<ll> in_T;
        ll prod2 = 1;
        int len = 0;
        for (int i = 0; i < vec.size(); i += 2) {
            len++;
            if (vec[i] == -1) {
                eval += prod;
                sum += prod;
                for (int j = cur.size() - 2; j >= 0; j--) {
                    cur[j] = min((ll)INF, cur[j] * cur[j + 1]);
                }
                reverse(all(cur));
                deq.push_back(cur);
                cur.clear();
                in_T.clear();
                prod2 = vec[i + 1];
                prod = vec[i + 1];
                cur.push_back(vec[i + 1]);
                in_T.push_back(vec[i + 1]);
            } else {
                prod = min((ll)INF, prod * vec[i + 1]);
                prod2 = prod2 * vec[i + 1];
                cur.push_back(vec[i + 1]);
                in_T.push_back(vec[i + 1]);
            }
            while (deq.size() && prod + sum > n) {
                sum -= deq.front().back();
                deq.front().pop_back();
                if (deq.front().empty())
                    deq.pop_front();
                else
                    sum += deq.front().back();
                len--;
            }
            // cout<<prod2<<endl;
            while (prod2 > n && in_T.size()) {
                prod2 /= in_T.front();
                in_T.pop_front();
            }
            if (deq.size())
                ans += len;
            else
                ans += in_T.size();
        }
        eval = min((ll)INF, eval + prod);
        // cout<<vec<<endl;
        // cout<<eval<<endl;
        return min((ll)INF, eval);
    };
    rec();
    return ans;
}

void solve() {
    int n;
    cin >> n;
    if (n == 0) exit(0);
    string s;
    cin >> s;
    // cerr<<calc(n,s)<<" "<<calc(n-1,s)<<endl;
    cout << calc(n, s) - calc(n - 1, s) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t = 1;
    // cin >> t;
    while (1) solve();
}
accuracy: 1
time_ms: 230
memory_kb: 74752
final_rank: 9

code_snippet: // C++ includes used for precompiling -*- C++ -*-
// Copyright (C) 2003-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://w...content-available-to-author-only...u.org/licenses/>.
/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */
// 17.4.1.2 Headers
// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>

#endif
using namespace std;
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T &a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T &a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline void compress(vector<T> &a) {
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
}
template <class T>
T rand(T l, T r) {
    static mt19937 mt(random_device{}());
    // [l, r)
    if constexpr (is_integral_v<T>) {
        return uniform_int_distribution<T>(l, r - 1)(mt);
    } else if constexpr (is_floating_point_v<T>) {
        return uniform_real_distribution<T>(l, r)(mt);
    }
}
constexpr int INF = 1001001001;
constexpr ll llINF = 3000000000000000010;
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint &operator+=(const modint &p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator-=(const modint &p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint &operator*=(const modint &p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint &operator/=(const modint &p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint &p) const { return modint(*this) += p; }
    modint operator-(const modint &p) const { return modint(*this) -= p; }
    modint operator*(const modint &p) const { return modint(*this) *= p; }
    modint operator/(const modint &p) const { return modint(*this) /= p; }
    bool operator==(const modint &p) const { return x == p.x; }
    bool operator!=(const modint &p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream &operator<<(ostream &os, const modint &p) { return os << p.x; }
    friend istream &operator>>(istream &is, modint &a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
ll extgcd(ll a, ll b, ll &x, ll &y) {
    // ax+by=gcd(|a|,|b|)
    if (a < 0 || b < 0) {
        ll d = extgcd(abs(a), abs(b), x, y);
        if (a < 0) x = -x;
        if (b < 0) y = -y;
        return d;
    }
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
template <class T>
vector<T> dijkstra(vector<vector<pair<int, T>>> &g, vector<int> start) {
    using P = pair<T, int>;
    vector<T> dp(g.size(), numeric_limits<T>::max());
    priority_queue<P, vector<P>, greater<P>> que;
    for (int s : start) {
        dp[s] = 0;
        que.push({0, s});
    }
    while (que.size()) {
        auto [d, v] = que.top();
        que.pop();
        if (dp[v] != d) continue;
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], d + c)) que.push({dp[u], u});
        }
    }
    return dp;
}

vector<int> BFS01(vector<vector<pair<int, int>>> &g, vector<int> start) {
    vector<int> dp(g.size(), numeric_limits<int>::max());
    deque<int> que;
    for (int s : start) {
        dp[s] = 0;
        que.push_front(s);
    }
    while (que.size()) {
        auto v = que.front();
        que.pop_front();
        for (auto [u, c] : g[v]) {
            if (chmin(dp[u], dp[v] + c)) {
                if (c == 0)
                    que.push_front(u);
                else
                    que.push_back(u);
            }
        }
    }
    return dp;
}
template <typename T, typename U>
inline istream &operator>>(istream &is, pair<T, U> &rhs) {
    return is >> rhs.first >> rhs.second;
}
template <typename T>
inline istream &operator>>(istream &is, vector<T> &v) {
    for (auto &e : v) is >> e;
    return is;
}
template <typename T, typename U>
inline ostream &operator<<(ostream &os, const pair<T, U> &rhs) {
    return os << rhs.first << " " << rhs.second;
}
template <typename T>
inline ostream &operator<<(ostream &os, const vector<T> &v) {
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr;) {
        os << *itr;
        if (++itr != end_itr) os << " ";
    }
    return os;
}

struct UnionFind {
    vector<int> par, siz;
    UnionFind(int x) {
        par.resize(x);
        siz.resize(x);
        for (int i = 0; i < x; i++) {
            par[i] = i;
            siz[i] = 1;
        }
    }
    int find(int x) {
        if (par[x] == x) return x;
        return par[x] = find(par[x]);
    }
    bool unite(int x, int y) {
        x = find(x), y = find(y);
        if (x == y) return false;
        if (siz[x] < siz[y]) swap(x, y);
        par[y] = x;
        siz[x] += siz[y];

        return true;
    }
    bool same(int x, int y) { return find(x) == find(y); }
    int size(int x) { return siz[find(x)]; }
};
template <class T>
struct BIT {
    // 1-indexed
    int n, beki = 1;
    vector<T> bit;
    BIT(int x) {
        bit.resize(x + 1, 0);
        n = x;
        while (beki * 2 <= n) beki *= 2;
    }
    T sum(int i) {
        T res = 0;
        while (i > 0) {
            res += bit[i];
            i -= i & -i;
        }
        return res;
    }
    T sum(int l, int r) {
        //[l,r]
        return sum(r) - (l == 0 ? 0 : sum(l - 1));
    }
    void add(int i, T x) {
        while (i <= n) {
            bit[i] += x;
            i += i & -i;
        }
    }
    int lowerbound(T w) {
        if (w <= 0) return 0;
        int x = 0;
        for (int k = beki; k > 0; k >>= 1) {
            if (x + k <= n && bit[x + k] < w) {
                w -= bit[x + k];
                x += k;
            }
        }
        return x + 1;
    }
};
using mint = modint<998244353>;
using State=string::iterator;
using F=pair<ll,ll>;
ll calc(ll n,string s){
    auto it=s.begin();
    ll ans=0;
    function<ll()>rec=[&](){
        //return evaluate value
        vector<int>vec;
        while(it!=s.end()&&*it!=')'){
            //cout<<*it<<endl;
            if(*it=='+'){
                vec.push_back(-1);
                it++;
            }
            else if(*it=='*'){
                vec.push_back(-2);
                it++;
            }
            else if(isdigit(*it)){
                vec.push_back(*it-'0');
                it++;
            }
            else if(*it=='('){
                it++;
                vec.push_back(rec());
                it++;
            }
            else assert(false);
        }
        ll sum=0;//<=n
        deque<vector<ll>>deq;
        ll prod=vec[0],eval=0;
        if(prod<=n)ans+=1;
        vector<ll>cur{vec[0]};
        deque<ll>in_T{vec[0]};
        ll prod2=vec[0];
        int len=1;
        for(int i=1;i<vec.size();i+=2){
            len++;
            if(vec[i]==-1){
                eval+=prod;
                sum+=prod;
                for(int j=cur.size()-2;j>=0;j--){
                    cur[j]=min((ll)INF,cur[j]*cur[j+1]);
                }
                reverse(all(cur));
                deq.push_back(cur);
                cur.clear();
                in_T.clear();
                prod2=vec[i+1];
                prod=vec[i+1];
                cur.push_back(vec[i+1]);
                in_T.push_back(vec[i+1]);
            }
            else{
                prod=min((ll)INF,prod*vec[i+1]);
                prod2=prod2*vec[i+1];
                cur.push_back(vec[i+1]);
                in_T.push_back(vec[i+1]);
            }
            while(deq.size()&&prod+sum>n){
               sum-=deq.front().back();
                deq.front().pop_back();
                if(deq.front().empty())deq.pop_front();
                else sum+=deq.front().back();
                len--;
            }
            //cout<<prod2<<endl;
            while(prod2>n&&in_T.size()){
                prod2/=in_T.front();
                in_T.pop_front();
            }
            if(deq.size())  ans+=len;
            else ans+=in_T.size();
        }
        eval=min((ll)INF,eval+prod);
        //cout<<vec<<endl;
        //cout<<eval<<endl;
        return min((ll)INF,eval);
    };
    rec();
    return ans;
}

void solve() {
    int n;
    cin>>n;
    if(n==0)exit(0);
    string s;
    cin>>s;
    //cerr<<calc(n,s)<<" "<<calc(n-1,s)<<endl;
    cout<<calc(n,s)-calc(n-1,s)<<endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t = 1;
    // cin >> t;
    while (1) solve();
}
accuracy: 1
time_ms: 220
memory_kb: 74516
final_rank: 7

code_snippet: #ifndef _DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
using namespace std;
#include <atcoder/all>
using namespace atcoder;
// #include <boost/rational.hpp>
// using namespace boost;
// using rat = rational<long long int>;
using mint = modint998244353;
// using mint = modint1000000007;
// using mint = mint;
using ll = long long;
using ld = long double;
using ull = uint64_t;
using pll = pair<ll, ll>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
using vm = vector<mint>;
using vvm = vector<vm>;
using vvvm = vector<vvm>;
using vstr = vector<string>;
#define v(T) vector<T>
#define vv(T) vector<vector<T>>
#define vvv(T) vector<vector<vector<T>>>
#define vvvv(T) vector<vector<vector<vector<T>>>>

istream &operator>>(istream &is, mint &a){ll tmp; is >> tmp; a = tmp; return is;}
ostream &operator<<(ostream &os, const mint &a){ os << a.val(); return os; }
string to_string(const __int128_t &a) { if (a == 0) return "0"; string s = ""; __int128_t num = a; bool is_negative = false; if (num < 0) { is_negative = true; num = -num; } while (num > 0) { s += '0' + (num % 10); num /= 10; } if (is_negative) s += '-'; reverse(s.begin(), s.end()); return s; }
istream &operator>>(istream &is, __int128_t &a){ string s; is >> s; a = 0; for(char c : s) { if(isdigit(c)) {a = a*10 + (c - '0'); }  } if(s[0]=='-'){ a *= -1; } return is; }
ostream &operator<<(ostream &os, const __int128_t &a){ os << to_string(a); return os; }
template<class T, class U> istream &operator>>(istream &is, pair<T, U> &p) { is >> p.first >> p.second; return is; }
template<class T, class U> ostream &operator<<(ostream &os, const pair<T, U> &p) { os << p.first << " " << p.second; return os; }
template<class T> istream &operator>>(istream &is, vector<T> &vec){ for(T &e : vec){is >> e;} return is; }
template<class T> ostream &operator<<(ostream &os, const vector<T> &vec) { for(int i = 0; i < (int)vec.size(); i++) { os << vec[i] << (i + 1 != (int)vec.size() ? " " : ""); } return os; }

template <class... T> constexpr auto min (T... a) { return min(initializer_list<common_type_t<T...>>{a...}); }
template <class... T> constexpr auto max (T... a) { return max(initializer_list<common_type_t<T...>>{a...}); }
template<class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
template<class T> T opmin(T x, T y) { return min(x, y); }
template<class T> T einf() { return numeric_limits<T>::max(); }
template<class T> T opmax(T x, T y) { return max(x, y); }
template<class T> T eminf() { return numeric_limits<T>::min(); }
template<class T> T opsum(T x, T y) { return x + y; }
template<class T> T ezero() { return (T)0; }
// #define maxseg(T) segtree<T, [](T x, T y){return max(x, y);}, [](){return (T)(-(1LL << 60));}>
// #define minseg(T) segtree<T, [](T x, T y){return min(x, y);}, [](){return (T)((1LL << 60));}>
// #define sumseg(T) segtree<T, [](T x, T y){return x + y;}, [](){return (T)(0);}>
template<class T> using minseg = segtree<T, opmin<T>, einf<T>>;
template<class T> using maxseg = segtree<T, opmax<T>, eminf<T>>;
template<class T> using sumseg = segtree<T, opsum<T>, ezero<T>>;
// template<class T> struct v : vector<T> { using vector<T> :: vector; };
// template<class T> struct vv : vector<v<T>> { using vector<v<T>> :: vector; };
// template<class T> struct vvv : vector<vv<T>> { using vector<vv<T>> :: vector; };
template<class T> inline bool chmin(T& a, T b) {if(a > b){a = b; return true;} else {return false;}};
template<class T> inline bool chmax(T& a, T b) {if(a < b){a = b; return true;} else {return false;}};
#define rep(i,n) for(ll i = 0; i < (ll)(n); i++)
#define repr(i,n) for(ll i = (ll)(n) - 1; i >= 0; i--)
#define REP(i, l, r) for(ll i = (ll)l; i <= (ll)(r); i++)
#define REPR(i, l, r) for(ll i = (ll)r; i >= (ll)(l); i--)
const ll inf = (1 << 30);
const ll INF = (1LL << 60);
const vector<pair<ll, ll>> DIJ = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};
void out(){cout<<'\n';}
template<class T, class... Ts> void out(const T& a, const Ts&... b){ cout<<a; (cout<<... << (cout << ' ', b)); cout << '\n';}
void outf(){cout<<endl;}
template<class T, class... Ts> void outf(const T& a, const Ts&... b){ cout<<a; (cout<<... << (cout << ' ', b)); cout << endl;}
template<class T, class U> void outp(pair<T, U> a){ out((a).first, (a).second); }
template<class T, class U> void outpf(pair<T, U> a){ outf((a).first, (a).second); }
template<class T> void outv(T a){rep(i, (a).size()){ cout << (a)[i] << " "; } cout << endl;}
template<class T> void outvL(T a){rep(i, (a).size()){out((a)[i]);} cout << flush; }
// template<class T> void outvv(T a){rep(i, a.size()){ rep(j, a.at(i).size()){cout << a.at(i).at(j) << " "; } cout << endl; }}
// template<class T> void outvp(T a){rep(i, a.size()){ out2(a.at(i).first, a.at(i).second); }}
void setpre(int a){cout << fixed << setprecision(a);}
#define outN out("No")
#define outY out("Yes")
#define outYN(flag) out(flag ? "Yes" : "No")
#define dame(...) {outf(__VA_ARGS__);return 0;}

template<class T> void read(vector<T>& vec){ for(int i = 0; i < (int)vec.size(); i++) { cin >> vec[i]; } }
template<class... T> void read(T&... a){(cin >> ... >> a);}
#define readll(...) ll __VA_ARGS__; read(__VA_ARGS__)
#define readvll(a, n) vector<ll> a(n); read(a)
#define readvt(type, a, n) vector<type> a(n); read(a)
#define readvll2(a, b, n) vector<ll> a(n), b(n); for(int lopi = 0; lopi < (int)(n); lopi++) cin >> (a)[lopi] >> (b)[lopi]
#define readvll3(a, b, c, n) vector<ll> a(n), b(n), c(n); for(int lopi = 0; lopi < (int)(n); lopi++) cin >> (a)[lopi] >> (b)[lopi] >> (c)[lopi]
#define readstr(...) string __VA_ARGS__; read(__VA_ARGS__)
#define readundirG(G, N, M) G = vvll(N); rep(lopi, M) {ll a, b; cin >> a >> b; G[a-1].push_back(b-1); G[b-1].push_back(a-1);}
#define readdirG(G, N, M) G = vvll(N); rep(lopi, M) {ll a, b; cin >> a >> b; G[a-1].push_back(b-1);}
#define readundirwghG(G, N, M) G = vv(pll)(N); rep(lopi, M) {ll a, b, c; cin >> a >> b >> c; G[a-1].emplace_back(b-1,c); G[b-1].emplace_back(a-1, c);}
#define readdirwghG (G, N, M) G = vv(pll)(N); rep(lopi, M) {ll a, b, c; cin >> a >> b >> c; G[a-1].emplace_back(b-1, c);}

#define All(a) (a).begin(), (a).end()
template<class T> inline void sortr(T& a){ sort((a).rbegin(), (a).rend()); }
template<class T> inline vector<int> argsort(T V, bool rev = false){vector<int> res(V.size()); iota(res.begin(), res.end(), 0); sort(res.begin(), res.end(), [&](int x, int y){if(!rev){return V[x] < V[y];}else{return V[x] > V[y];}}); return res;}
template<class T, class U> inline void sort_by_idx(T& V, vector<U>& I){assert(V.size() == I.size()); T tmpv = V; for(int loopi = 0; loopi < (int)I.size(); loopi++){V[loopi] = tmpv[I.at(loopi)];}}
template<class T, class U> inline void sortp(vector<T>& v1, vector<U>& v2, bool rev1 = false, int rev2 = false){assert(v1.size() == v2.size()); vector<int> I(v1.size()); iota(I.begin(), I.end(), 0); sort(I.begin(), I.end(), [&](const int x, const int y){if(v1[x] != v1[y]){return (bool)(rev1 ^ (v1[x] < v1[y]));}else{if(v2[x]==v2[y]){return false;} return (bool)(rev2 ^ (v2[x] < v2[y]));}}); sort_by_idx(v1, I); sort_by_idx(v2, I);}
template<class T> T POW(T x, ll n) {T ret = 1; while(n > 0){if(n & 1) ret *= x; x *= x; n >>= 1;} return ret;}
ll powll(ll x, ll n){ll ret = 1; while(n > 0){if(n & 1) ret *= x; x *= x; n >>= 1;} return ret;}
inline ll divceil(ll x, ll y) { if(x >= 0) {return(x / y + (ll)(x % y != 0)); } else { return -((-x) / y); } }
inline ll divfloor(ll x, ll y) { if(x >= 0) { return x/y; } else { return -((-x)/y + (ll)((-x) % y != 0)); } }
inline bool inLR(ll x, ll L, ll R){ return (L <= x && x < R); }
inline bool inRect(ll pos_x, ll pos_y, ll rect_H, ll rect_W, ll rect_h = 0, ll rect_w = 0){ return (rect_h <= pos_x && pos_x < rect_H && rect_w <= pos_y && pos_y < rect_W); }

template<class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v){e++;} return v;}
template<class T> vector<T> operator++(vector<T> &v, signed) {auto res=v; for(auto &e : v){e++;} return res;}
template<class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v){e--;} return v;}
template<class T> vector<T> operator--(vector<T> &v, signed) {auto res=v; for(auto &e : v){e--;} return res;}
template<class T> vector<T> operator+(const vector<T> &x, const vector<T> &y) { assert(x.size() == y.size()); vector<T> ret(x.size()); for(int i = 0; i < (int)x.size(); i++) {ret[i] = x[i] + y[i];} return ret; }
template<class T> vector<T> operator-(const vector<T> &x, const vector<T> &y) { assert(x.size() == y.size()); vector<T> ret(x.size()); for(int i = 0; i < (int)x.size(); i++) {ret[i] = x[i] - y[i];} return ret; } 

template<class T, class U> pair<T, U> operator+(const pair<T, U> &x, const pair<T, U> &y) { return make_pair(x.first + y.first, x.second + y.second); }
template<class T, class U> pair<T, U> operator-(const pair<T, U> &x, const pair<T, U> &y) { return make_pair(x.first - y.first, x.second - y.second); }
template<class T, class U> void operator+=(pair<T, U> &x, pair<T, U> &y) { x = x + y; }
template<class T, class U> void operator-=(pair<T, U> &x, pair<T, U> &y) { x = x - y; }

template<class T> size_t HashCombine(const size_t seed,const T &v){ return seed^(std::hash<T>()(v)+0x9e3779b9+(seed<<6)+(seed>>2)); }
template<class T,class S> struct std::hash<std::pair<T,S>>{ size_t operator()(const std::pair<T,S> &keyval) const noexcept { return HashCombine(std::hash<T>()(keyval.first), keyval.second); } };
template<class T> struct std::hash<std::vector<T>>{ size_t operator()(const std::vector<T> &keyval) const noexcept { size_t s=0; for (auto&& v: keyval) s=HashCombine(s,v); return s; } };
template<int N> struct HashTupleCore{ template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{ size_t s=HashTupleCore<N-1>()(keyval); return HashCombine(s,std::get<N-1>(keyval)); } };
template <> struct HashTupleCore<0>{ template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{ return 0; } };
template<class... Args> struct std::hash<std::tuple<Args...>>{ size_t operator()(const tuple<Args...> &keyval) const noexcept { return HashTupleCore<tuple_size<tuple<Args...>>::value>()(keyval); } };

using lll = __int128_t;

int main()
{
    std::cin.tie(nullptr), std::ios_base::sync_with_stdio(false);
    while(true)
    {
        readll(N);
        if(!N) break;
        readstr(S);
        ll M = S.size();
        vll f(M, -1);
        stack<ll> st;
        rep(i, M)
        {
        if(S[i] == '(')
        {
            st.push(i);
        }
        else if(S[i] == ')')
        {
            f[st.top()] = i;
            st.pop();
        }
        }
        ll ans = 0;
        // outf(f);
        function<string(ll, ll)> dfs = [&](ll l, ll r)
        {
        // outf(l, r);
        vstr V;
        ll i = l;
        while(i < r)
        {
            if(S[i] == '(')
            {
            string ns = dfs(i + 1, f[i]);
            // outf(ns);
            i = f[i] + 1;
            V.emplace_back(ns); 
            }
            else
            {
            V.push_back(S.substr(i, 1));
            i++;
            }
        }
        lll sum = 0;
        ll li = 0, ri = 0;
        ll n = V.size();
        char op = '*';
        deque<pair<lll, queue<lll>>> Q;
        bool ninf = false;
        // outf(V);
        bool alln = false;
        ll rcnt1 = 0;
        while(li < n)
        {
            // outf(li, ri);
            chmax(ri, li);
            if(ri >= n) break;
            while(sum < N && ri < n)
            {
            if(V[ri] == "+")
            {
                op = '+';
                ri++;
                rcnt1 = 0;
            }
            else if(V[ri] == "*")
            {
                op = '*';
                ri++;
            }
            else
            {
                if(V[ri] == "inf")
                {
                ninf = true;
                Q.clear();
                sum = 0;
                li = ri + 2;
                ri = li;
                rcnt1 = 0;
                break;
                }
                else
                {
                lll ns = stoll(V[ri]);
                // outf("ns=", ns);
                if(op == '+')
                {
                    if(ns == 1) rcnt1++;
                    else rcnt1 = 0;
                    sum += ns;
                    queue<lll> tmp;
                    tmp.push(ns);
                    Q.emplace_back(ns, tmp);
                    ri++;
                }
                else
                {
                    if(ns == 1) rcnt1++;
                    else rcnt1 = 0;
                    if(Q.empty())
                    {
                    sum += ns;
                    queue<lll> tmp;
                    tmp.push(ns);
                    Q.emplace_back(ns, tmp);
                    }
                    else
                    {
                    sum -= Q.back().first;
                    Q.back().first *= ns;
                    Q.back().second.push(ns);
                    sum += Q.back().first;
                    }
                    ri++;
                }
                }
            }
            }
            while(ri + 1 < n)
            {
            if(V[ri] == "*" && V[ri + 1] == "1")
            {
                op = '*';
                rcnt1++;
                if(Q.empty())
                {
                sum += 1;
                queue<lll> tmp;
                tmp.push(1);
                Q.emplace_back(1, tmp);
                }
                else
                {
                sum -= Q.back().first;
                Q.back().first *= 1;
                Q.back().second.push(1);
                sum += Q.back().first;
                }
                ri += 2;
            }
            else
            {
                break;
            }
            }
            // outf(li, ri, "sum =", sum, "rcnt =", rcnt1);
            if(li == 0 && ri == n && sum == N) alln = true;
            while(!Q.empty() && sum >= N)
            {
            if(sum >= N) ninf = true;
            if(sum == N)
            {
                if(N > 1) ans += rcnt1 + ((Q.back().first == 1) ? 0 : 1);
                else ans += rcnt1;
            }
            if(sum == 1 && Q.front().second.front() == 1) rcnt1--;
            sum -= Q.front().first;
            if(Q.front().second.size() == 1)
            {
                Q.pop_front();
            }
            else
            {
                // outf(Q.front().second.front());
                Q.front().first /= Q.front().second.front();
                Q.front().second.pop();
                sum += Q.front().first;
            }
            li += 2;
            }
            // outf(li, ri, ans);
        }
        string ret = to_string(sum);
        // if(!alln && !ninf && ret == "0") outf(li, ri, V);
        // outf(ans);
        if(alln) return to_string(N);
        else if(ninf ) return string{"inf"};
        else return ret;
        };
        string teststr = dfs(0, M);
        outf(ans);
    }  
}
accuracy: 1
time_ms: 890
memory_kb: 811848
final_rank: 18

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>

using namespace std;
using ll = long long;
using pll = pair<ll,ll>;
using bint = __int128_t;
#define rep(i, s, t) for (ll i = s; i < (ll)(t); i++)
#define rrep(i, s, t) for(ll i = (ll)(t) - 1; i >= (ll)(s); i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define TT template<typename T>
TT using vec = vector<T>;
TT using minheap = priority_queue<T, vector<T>, greater<T>>;
TT using maxheap = priority_queue<T>;
template<class T> bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }
template<class T> bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }
struct io_setup {
    io_setup() {
        ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        cout << fixed << setprecision(15);
    }
} io_setup;

std::ostream &operator<<(std::ostream &dest, __int128_t value) {
  std::ostream::sentry s(dest);
  if (s) {
    __uint128_t tmp = value < 0 ? -value : value;
    char buffer[128];
    char *d = std::end(buffer);
    do {
      --d;
      *d = "0123456789"[tmp % 10];
      tmp /= 10;
    } while (tmp != 0);
    if (value < 0) {
      --d;
      *d = '-';
    }
    int len = std::end(buffer) - d;
    if (dest.rdbuf()->sputn(d, len) != len) {
      dest.setstate(std::ios_base::badbit);
    }
  }
  return dest;
}

__int128 parse(string &s) {
  __int128 ret = 0;
  for (size_t i = 0; i < s.length(); i++)
    if ('0' <= s[i] && s[i] <= '9')
      ret = 10 * ret + s[i] - '0';
  return ret;
}

std::istream &operator>>(std::istream &dest, __int128_t &value) {
    string s;
    dest >> s;
    value = parse(s);
    return dest;
}

ll N;

tuple<map<ll,ll>,map<ll,ll>,ll> buildv(const vector<ll> &v){
  ll sm=1;
  for(ll c:v) sm=min(N+1,sm*c);
  map<ll,ll> st,ed;
  ll tmp=1;
  int m=v.size();
  rep(i,0,m){
    tmp*=v[i];
    if(tmp>N) break;
    ed[tmp]++;
  }
  tmp=1;
  rep(i,0,m){
    tmp*=v[m-1-i];
    if(tmp>N) break;
    st[tmp]++;
  }
  return {st,ed,sm};
}
using state = string::iterator;
ll E(state& itr);
vector<ll> T(state &itr);
ll F(state &itr);

ll F(state &itr){
  if(*itr=='('){
    itr++;
    ll res=E(itr);
    assert(*itr==')');
    itr++;
    return res;
  }else{
    return *(itr++)-'0';
  }
}
ll ans=0;
vector<ll> T(state &itr){
  vector<ll> Fs;
  Fs.push_back(F(itr));
  map<ll,ll> st;
  st[Fs[0]]++;
  if(st.count(N)) ans+=st[N];
  while(*itr=='*'){
    itr++;
    ll res=F(itr);
    if(res!=1){
      map<ll,ll> nst;
      for(auto[x,ad]:st){
        if(x*res>N) break;
        nst[x*res]+=ad;
      }
      swap(nst,st);
    }
    if(res<=N) st[res]++;
    if(st.count(N)) ans+=st[N];
    Fs.push_back(res);
  }
  return Fs;
}
ll E(state &itr){
  auto v=T(itr);
  auto[start,end,sum]=buildv(v);
  ll tmp=0;
  while(*itr=='+'){
    itr++;
    auto[st,ed,sm]=buildv(T(itr));
    for(auto[x,ad]:ed){
      if(start.count(N-x-tmp)) ans+=start[N-x-tmp]*ad;
    }
    tmp+=sm;
    for(auto[x,ad]:st){
      start[x-tmp]+=ad;
    }
  };
  return min(N+1,sum+tmp);
}

int solve(){
  cin>>N;
  if(N==0) return 0;
  string s;
  cin>>s;
  state itr=s.begin();
  ans=0;
  E(itr);
  cout<<ans<<"\n";
  return 1;
}

int main() {
  while(solve());
}
accuracy: 1
time_ms: 720
memory_kb: 70000
final_rank: 13

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

ll ANS;
int it;
ll N;
string S;

ll Expr();
ll Factor();

void BugSearch(string _) {
    //cout << _ << ": " << it << endl;
}

ll Expr() {
    BugSearch("Expr");
    vector<ll> V;
    vector<int> Op;
    V.push_back(Factor());
    while(S[it] == '+' || S[it] == '*') {
        if (S[it] == '+') Op.push_back(0);
        else Op.push_back(1);
        it++;
        V.push_back(Factor());
    }
    int M = V.size();
    int L = 0, R = 0, ONES = 0;
    deque<ll> Q;
    ll Cur;
    while(L < M) {
        if (R <= L+1) {
            if (V[L] == 1) ONES = 1;
            else ONES = 0;
            Cur = V[L];
            Q.clear();
            Q.push_front(Cur);
            R = L+1;
        }
        while (Cur < N && R < M) {
            if (Op[R-1] == 0) {
                if (V[R] == 1) ONES = 1;
                else ONES = 0;
                Cur += V[R];
                Q.push_back(V[R]);
                R++;
            }
            else {
                if (V[R] == 1) ONES++;
                else ONES = 0;
                Cur += Q.back() * (V[R] - 1);
                Q.back() *= V[R];
                R++;
            }
        }
        if (Cur == N) {
            if (R > 0 && V[R-1] != 1) ONES = 0;
            if (R < M && V[R] == 1 && R > 0 && Op[R-1] == 1) {
                while(R < M && V[R] == 1 && R > 0 && Op[R-1] == 1) {
                    ONES++;
                    R++;
                }
            }
            int Left;
            if (Q.back() == 1) Left = R - (ONES - 1);
            else Left = R - ONES;
            ANS += R - max(L + 2, Left) + 1;
        }
        if (L >= M-1) {
            Cur = 0;
            Q.clear();
        }
        else if (Op[L] == 0) {
            Cur -= V[L];
            Q.pop_front();
        }
        else {
            Cur -= Q.front();
            Cur += Q.front() / V[L];
            Q.front() /= V[L];
        }
        L++;
        chmin(ONES, R-L);
    }
    vector<ll> Term;
    Term.push_back(V[0]);
    rep(i,1,M) {
        if (Op[i-1] == 0) {
            Term.push_back(V[i]);
        }
        else {
            Term.back() *= V[i];
            chmin(Term.back(), (ll)inf);
        }
    }
    ll Ret = 0;
    rep(i,0,Term.size()) {
        Ret += Term[i];
        chmin(Ret, (ll)inf);
    }
    return Ret;
}

ll Factor() {
    BugSearch("Factor");
    if (S[it] == '(') {
        it++;
        ll Ret = Expr();
        it++;
        if (Ret == N) ANS++;
        return Ret;
    }
    else {
        ll Ret = S[it] - '0';
        it++;
        if (Ret == N) ANS++;
        return Ret;
    }
}

int main() {
while(1) {
    cin >> N;
    if (N == 0) return 0;
    cin >> S;
    S += '$';
    ANS = 0;
    it = 0;
    Expr();
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 100
memory_kb: 39632
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)
#define RREP(i,n) RFOR(i,0,n)
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (upper_bound(ALL(A),x)-A.begin())
struct segtree{
    ll n;
    vector<ll>tree;
    segtree(ll N){
        n=1;
        while(n<N)n*=2;
        tree.assign(2*n,1);
    }
    void set(ll i,ll x){
        i+=n;
        tree[i]=x;
        while(i){
            tree[i/2]=min(tree[i]*tree[i^1],1000000100LL);
            i/=2;
        }
    }
    ll prod(ll l,ll r){
        assert(0<=l&&l<=r&&r<=n);
        l+=n;r+=n;
        ll res=1;
        while(l<r){
            if(l%2)res*=tree[l++];
            if(res>1000000000LL)break;
            if(r%2)res*=tree[--r];
            if(res>1000000000LL)break;
            l/=2;r/=2;
        }
        return res;
    }
};
int main(){
    while(1){
        ll x;string S;cin>>x>>S;
        ll N=S.size();
        if(!x)return 0;
        vector<int>par(N);
        stack<int>st;
        REP(i,N){
            if(S[i]=='(')st.emplace(i);
            if(S[i]==')')par[st.top()]=i,st.pop();
        }
        ll ans=0;
        function<ll(ll,ll)>dfs=[&](ll l,ll r){
            vector<ll>V;
            string op;
            FOR(i,l,r){
                if(S[i]=='(')V.emplace_back(dfs(i+1,par[i])),i=par[i]+1;
                else V.emplace_back(S[i]-'0'),i++;
                if(i==r)break;
                op+=S[i];
            }
            vector<vector<ll>>A;
            vector<ll>P;
            REP(i,V.size()){
                vector<ll>a={V[i]};
                ll pro=V[i];
                while(i<op.size()&&op[i]=='*')a.emplace_back(V[++i]),pro=min(x+10,pro*V[i]);
                A.emplace_back(a);
                P.emplace_back(pro);
            }
            vector<vector<ll>>S=A;
            vector<ll>B(P.size()+1);
            REP(i,P.size())B[i+1]=B[i]+P[i];
            REP(i,P.size())FOR(j,1,A[i].size())S[i][j]=min(x+10,S[i][j]*S[i][j-1]);
            REP(i,P.size()){
                if(B.back()-B[i]>=x){
                    vector<ll>T=A[i];
                    RREP(j,T.size()-1)T[j]=min(x+10,T[j+1]*T[j]);
                    REP(j,T.size())if(T[j]+B.back()-B[i+1]>=x&&T[j]<x){
                        ll t=LB(B,-T[j]+B[i+1]+x);
                        ll val=B[t-1]-B[i+1]+T[j];
                        ans+=UB(S[t-1],x-val)-LB(S[t-1],x-val);
                    }
                }
                segtree seg(A[i].size());
                REP(j,A[i].size())seg.set(j,A[i][j]);
                REP(j,A[i].size()){
                    ll l=j,r=A[i].size();
                    while(r-l>1){
                        ll m=(l+r)/2;
                        if(seg.prod(j,m)<x)l=m;
                        else r=m;
                    }
                    if(seg.prod(j,r)!=x)continue;
                    ll p=l;
                    r=A[i].size()+1;
                    while(r-l>1){
                        ll m=(l+r)/2;
                        if(seg.prod(j,m)<=x)l=m;
                        else r=m;
                    }
                    ans+=l-p;
                }
            }
            //cout<<l<<" "<<r<<"->"<<ans<<endl;
            return min(x+10,B.back());
        };
        dfs(0,N);
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 470
memory_kb: 151336
final_rank: 14

code_snippet: #line 1 "A.cpp"
#line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

i64 solve(int X) {
    string s = in();
    s = "(" + s + ")";

    i64 ans = 0;
    int i = 0;
    const i64 INF = 1e9 + 1;
    auto dfs = [&](auto self) -> i64 {
        assert(s[i] == '('); i++;
        vector<i64> num;
        vector<char> op = {'+'};
        while(s[i] != ')') {
            if(s[i] == '(') {
                num.push_back(self(self));
            } else if(std::isdigit(s[i])) {
                num.push_back(s[i] - '0'); i++;
            } else if(s[i] == '+' or s[i] == '*') {
                op.push_back(s[i]); i++;
            } else {
                assert(0);
            }
        }
        assert(s[i] == ')'); i++;

        // count
        const int m = op.size();
        op.push_back('+');

        if(X == 1) {
            vector<i64> vec = {0};
            for(int k : rep(m)) {
                if(num[k] == 1) {
                    if(op[k] == '+') {
                        vec.push_back(1);
                    } else {
                        vec.back() += 1;
                    }
                } else {
                    vec.push_back(0);
                }
            }
            for(i64 x : vec) ans += (x + 1) * x / 2;
        } else {
            vector<i64> one_cnt(m); {
                i64 cnt = 0;
                for(int k : rep(m)) {
                    if(num[k] == 1 and op[k] == '*') {
                        cnt++;
                    } else {
                        cnt = 0;
                    }
                    one_cnt[k] = cnt;
                }
            }

            deque<i64> dq;
            i64 value = 0;
            for(int L = 0, R = 0; L < m; L++) {
                while(R < m) {
                    if(dq.empty()) {
                        dq.push_back(num[R]);
                        value += num[R];
                        R++;
                    } else {
                        if(op[R] == '+') {
                            if(value + num[R] <= X) {
                                dq.push_back(num[R]);
                                value += num[R];
                                R++;
                            } else break;
                        } else {
                            if(value - dq.back() + dq.back() * num[R] <= X) {
                                value = value - dq.back() + dq.back() * num[R];
                                dq.back() *= num[R];
                                R++;
                            } else break;
                        }
                    }
                }

                if(value == X) {
                    ans += one_cnt[R - 1] + 1;
                }
                
                if(L + 1 == R) {
                    value = 0;
                    dq.pop_front();
                } else {
                    if(op[L + 1] == '+') {
                        value -= dq.front();
                        dq.pop_front();
                    } else {
                        value = value - dq.front() + dq.front() / num[L];
                        dq.front() /= num[L];
                    }
                }
            }
        }

        // eval
        vector<i64> ts = {num[0]};
        for(int k : rep(1, m)) {
            if(op[k] == '+') {
                ts.push_back(num[k]);
            } else {
                ts.back() *= num[k];
                chmin(ts.back(), INF);
            }
        }
        i64 sum = 0;
        for(i64 t : ts) sum += t;
        return min(sum, INF);
    };
    dfs(dfs);
    return ans;
}

int main() {
    while(true) {
        int n = in(); if(n == 0) return 0;
        print(solve(n));
    }
}
accuracy: 1
time_ms: 50
memory_kb: 33828
final_rank: 1

code_snippet: #line 1 "A.cpp"
#line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

i64 solve(int X) {
    string s = in();
    s = "(" + s + ")";

    i64 ans = 0;
    int i = 0;
    const i64 INF = 1e9 + 1;
    auto dfs = [&](auto self) -> i64 {
        assert(s[i] == '('); i++;
        vector<i64> num;
        vector<char> op = {'+'};
        while(s[i] != ')') {
            if(s[i] == '(') {
                num.push_back(self(self));
            } else if(std::isdigit(s[i])) {
                num.push_back(s[i] - '0'); i++;
            } else if(s[i] == '+' or s[i] == '*') {
                op.push_back(s[i]); i++;
            } else {
                assert(0);
            }
        }
        assert(s[i] == ')'); i++;

        // count
        const int m = op.size();
        op.push_back('+');

        if(X == 1) {
            vector<i64> vec = {0};
            for(int k : rep(m)) {
                if(num[k] == 1) {
                    if(op[k] == '+') {
                        vec.push_back(1);
                    } else {
                        vec.back() += 1;
                    }
                } else {
                    vec.push_back(0);
                }
            }
            for(i64 x : vec) ans += (x + 1) * x / 2;
        } else {
            vector<i64> one_cnt(m); {
                i64 cnt = 0;
                for(int k : rep(m)) {
                    if(num[k] == 1 and op[k] == '*') {
                        cnt++;
                    } else {
                        cnt = 0;
                    }
                    one_cnt[k] = cnt;
                }
            }

            deque<i64> dq;
            i64 value = 0;
            for(int L = 0, R = 0; L < m; L++) {
                while(R < m) {
                    if(dq.empty()) {
                        dq.push_back(num[R]);
                        value += num[R];
                        R++;
                    } else {
                        if(op[R] == '+') {
                            if(value + num[R] <= X) {
                                dq.push_back(num[R]);
                                value += num[R];
                                R++;
                            } else break;
                        } else {
                            if(value - dq.back() + dq.back() * num[R] <= X) {
                                value = value - dq.back() + dq.back() * num[R];
                                dq.back() *= num[R];
                                R++;
                            } else break;
                        }
                    }
                }

                if(value == X) {
                    ans += one_cnt[R - 1] + 1;
                }
                
                if(L + 1 == R) {
                    value = 0;
                    dq.pop_front();
                } else {
                    if(op[L + 1] == '+') {
                        value -= dq.front();
                        dq.pop_front();
                    } else {
                        value = value - dq.front() + dq.front() / num[L];
                        dq.front() /= num[L];
                    }
                }
            }
        }

        // eval
        vector<i64> ts = {num[0]};
        for(int k : rep(1, m)) {
            if(op[k] == '+') {
                ts.push_back(num[k]);
            } else {
                ts.back() *= num[k];
                chmin(ts.back(), INF);
            }
        }
        i64 sum = 0;
        for(i64 t : ts) sum += t;
        return min(sum, INF);
    };
    dfs(dfs);
    return ans;
}

int main() {
    while(true) {
        int n = in(); if(n == 0) return 0;
        print(solve(n));
    }
}
accuracy: 1
time_ms: 50
memory_kb: 33840
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;

constexpr int LG_LENGTH = 22;
constexpr int MAX_DEPTH = 1001;
constexpr int INF = 1LL << 30;

template <auto op, auto e> struct dynamic_doubling {
  int sz;
  long long all_prod;
  vector<vector<int>> dest;
  vector<vector<int>> cost;
  dynamic_doubling() {
    sz = 0;
    all_prod = e();
    dest.push_back(vector<int>(LG_LENGTH, 0));
    cost.push_back(vector<int>(LG_LENGTH, INF));
  }
  void push_back(int v) {
    all_prod = op(all_prod, v);
    vector<int> dest_cur(LG_LENGTH, 0);
    vector<int> cost_cur(LG_LENGTH, INF);
    dest_cur[0] = sz;
    cost_cur[0] = v;
    for(int i = 0; i + 1 < LG_LENGTH; i++) {
      dest_cur[i + 1] = dest[dest_cur[i]][i];
      cost_cur[i + 1] = op(cost[dest_cur[i]][i], cost_cur[i]);
    }
    sz++;
    dest.push_back(dest_cur);
    cost.push_back(cost_cur);
  }
  pair<int, int> min_left(int v) {
    if(v <= e()) {
      return make_pair(sz, 0);
    }
    int l = sz;
    int cost_cur = e();
    for(int i = LG_LENGTH - 1; i >= 0; i--) {
      if(op(cost_cur, cost[l][i]) < v) {
        cost_cur = op(cost_cur, cost[l][i]);
        l = dest[l][i];
      }
    }
    return make_pair(l, cost_cur);
  }
};

int add_e() {
  return 0;
}
int add(int x, int y) {
  if(x <= INF - y) return x + y;
  return INF;
}

int mul_e() {
  return 1;
}
int mul(int x, int y) {
  if(x <= INF / y) return x * y;
  return INF;
}

bool solve() {
  int n;
  cin >> n;
  if(n == 0) return false;
  string s;
  cin >> s;
  long long ans = 0;
  vector<dynamic_doubling<add, add_e>> dbl_add;
  vector<vector<dynamic_doubling<mul, mul_e>>> dbl_mul;
  dbl_add.push_back(dynamic_doubling<add, add_e>());
  dbl_mul.push_back(vector<dynamic_doubling<mul, mul_e>>{dynamic_doubling<mul, mul_e>()});
  for(int i = 0, d = 0; i < int(s.size()); i++) {
    if(isdigit(s[i])) {
      dbl_mul[d].back().push_back(s[i] - '0');
    }else if(s[i] == '(') {
      d++;
      dbl_add.push_back(dynamic_doubling<add, add_e>());
      dbl_mul.push_back(vector<dynamic_doubling<mul, mul_e>>());
      dbl_mul[d].push_back(dynamic_doubling<mul, mul_e>());
      continue;
    }else if(s[i] == ')') {
      const long long eval_all = add(dbl_add[d].all_prod, dbl_mul[d].back().all_prod);
      d--;
      dbl_mul[d].back().push_back(eval_all);
      dbl_add.pop_back();
      dbl_mul.pop_back();
    }else if(s[i] == '+') {
      if(dbl_mul[d].back().sz > 0) {
        dbl_add[d].push_back(dbl_mul[d].back().all_prod);
        dbl_mul[d].push_back(dynamic_doubling<mul, mul_e>());
      }
      continue;
    }else if(s[i] == '*') {
      continue;
    }
    const int add_ap = dbl_add[d].all_prod;
    const int mul_ap = dbl_mul[d].back().all_prod;
    // cout << add_ap << " " << mul_ap << endl;
    if(add(add_ap, mul_ap) < n) {
      // do nothing
    }else if(mul_ap >= n) {
      auto [lm1, cm1] = dbl_mul[d].back().min_left(n + 1);
      auto [lm2, cm2] = dbl_mul[d].back().min_left(n);
      if(cm1 == n) ans += lm2 - lm1;
    }else {
      auto [la1, ca1] = dbl_add[d].min_left(n - mul_ap);
      auto [lm1, cm1] = dbl_mul[d][la1 - 1].min_left(n + 1 - ca1 - mul_ap);
      auto [lm2, cm2] = dbl_mul[d][la1 - 1].min_left(n - ca1 - mul_ap);
      // cout << n + 1 - ca1 - mul_ap << endl;
      // cout << la1 << " " << lm1 << " " << lm2 << endl;
      // cout << ca1 << " " << cm1 << " " << mul_ap << endl;
      if(add(cm1, add(ca1, mul_ap)) == n) ans += lm2 - lm1;
    }
  }
  cout << ans << endl;
  return true;
}

int main() {
  while(solve()) {}
}
accuracy: 1
time_ms: 4170
memory_kb: 805072
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()
ll eval(vll D) {
    ll res = 0;
    ll N = D.size();
    ll pr = 1;
    rep(i, N) {
        if (D[i] >= 0) {
            pr *= D[i];
            if (pr > 1e9)pr = 1e9 + 1;
        }
        else if (D[i] == -1) {
            res += pr;
            if (res > 1e9)res = 1e9 + 1;
            pr = 1;
        }
    }
    res += pr;
    return min(res, ll(1e9 + 1));
}



vector<pair<ll, ll>> compress(vll D) {
    ll N = D.size();
    vector<pair<ll, ll>> ND(N);
    rep(i, N) {
        ND[i].first = D[i];
        ND[i].second = 1;
    }
    reverse(all(ND));
    ll cnt = 0;
    for (ll i = 0; i < N; i += 2) {
        if (i==N-1||ND[i].first != 1 || (i != N - 1 && ND[i + 1].first == -1)) {
            ND[i].second += cnt;
            cnt = 0;
        }
        else cnt++;
    }
    reverse(all(ND));
    return ND;
}

ll calc(vll D, ll T) {
    ll N = D.size();
    bool is_all_oneprod = 1;
    rep(i, N) {
        if (i % 2 == 0 && D[i] != 1)is_all_oneprod = 0;
        if (i % 2 == 1 && D[i] != -2)is_all_oneprod = 0;
    }
    if (is_all_oneprod) {
        if (T == 1) {
            return (N / 2 + 2) * (N / 2 + 1) / 2;
        }
        else return 0;
    }
    auto ND = compress(D);
    N = ND.size();
    deque<ll> P;
    deque<ll> index;
    ll res = 0;
    ll cnt = 0;
    ll R = 0;
    for (ll i = 0; i < N; i += 2) {
        while (res < T && R < N) {
            index.push_back(R);
            if (P.size() == 0 || ND[R - 1].first == -1) {
                P.push_back(ND[R].first);
                res += ND[R].first;
            }
            else {
                res -= P.back();
                P.back() *= ND[R].first;
                res += P.back();
            }
            R += 2;
        }
        if (res == T) {
            ll rid = index.back();
            cnt += ND[rid].second;
        }
        if (index.size() == 0)break;
        ll r = index.front();
        index.pop_front();
        if (index.size()==0||(r != N - 1 && ND[r + 1].first == -1)) {
            P.pop_front();
            res -= ND[r].first;
        }
        else {
            res -= P.front();
            //assert(0 <= r && r < N);
            P.front() /= ND[r].first;

            res += P.front();
        }
    }
    return cnt;
}

void solve(ll N) {
    string S;
    cin >> S;
    ll SN = S.size();
    vector<vll> D(SN + 1);
    //-1:+, -2:*

    ll an = 0;
    ll cnt = 0;
    rep(i, SN) {
        if (S[i] == '(')cnt++;
        else if (S[i] == ')') {
            an += calc(D[cnt], N);
            ll res = eval(D[cnt]);
            D[cnt] = {};
            D[cnt - 1].push_back(res);
            cnt--;
        }
        else if (S[i] == '+') {
            D[cnt].push_back(-1);
        }
        else if (S[i] == '*') {
            D[cnt].push_back(-2);
        }
        else {
            D[cnt].push_back(S[i] - '0');
        }
    }
    an += calc(D[0], N);
    cout << an << endl;
}

int main() {

    ll N;
    ll couutn = 0;
    while (cin >> N) {
        if (N == 0)return 0;
        couutn++;
        // if (couutn == 40)cout << "#" << N << endl;;
        solve(N);
    }
}
accuracy: 1
time_ms: 150
memory_kb: 150216
final_rank: 12

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()
ll eval(vll D) {
    ll res = 0;
    ll N = D.size();
    ll pr = 1;
    rep(i, N) {
        if (D[i] >= 0) {
            pr *= D[i];
            if (pr > 1e9)pr = 1e9+1;
        }
        else if (D[i] == -1) {
            res += pr;
            if (res > 1e9)res = 1e9+1;
            pr = 1;
        }
    }
    res += pr;
    return min(res, ll(1e9+1));
}



vector<pair<ll, ll>> compress(vll D) {
    ll N = D.size();
    vector<pair<ll, ll>> ND(N);
    rep(i, N) {
        ND[i].first = D[i];
        ND[i].second = 1;
    }
    reverse(all(ND));
    ll cnt = 0;
    for (ll i = 0; i < N; i += 2) {
        if (ND[i].first != 1 || (i != N - 1 && ND[i + 1].first == -1)) {
            ND[i].second += cnt;
            cnt = 0;
        }
        else cnt++;
    }
    reverse(all(ND));
    return ND;
}

ll calc(vll D, ll T) {
    ll N = D.size();
    bool is_all_oneprod = 1;
    rep(i, N) {
        if (i % 2 == 0 && D[i] != 1)is_all_oneprod = 0;
        if (i % 2 == 1 && D[i] != -2)is_all_oneprod = 0;
    }
    if (is_all_oneprod) {
        if (T == 1) {
            return (N / 2 + 2) * (N / 2 + 1) / 2;
        }
        else return 0;
    }
    auto ND = compress(D);
    N = ND.size();
    deque<ll> P;
    deque<ll> index;
    ll res = 0;
    ll cnt = 0;
    ll R = 0;
    for (ll i = 0; i < N; i += 2) {
        while (res < T && R < N) {
            index.push_back(R);
            if (P.size() == 0 || ND[R - 1].first == -1) {
                P.push_back(ND[R].first);
                res += ND[R].first;
            }
            else {
                res -= P.back();
                P.back() *= ND[R].first;
                res += P.back();
            }
            R += 2;
        }
        if (res == T) {
            ll rid = index.back();
            cnt += ND[rid].second;
        }
        if(index.size()==0)break;
        ll r = index.front();
        index.pop_front();
        if (r != N - 1 && ND[r + 1].first == -1) {
            P.pop_front();
            res -= ND[r].first;
        }
        else {
            res -= P.front();
            assert(0<=r&&r<N);
            P.front() /= ND[r].first;
            
            res += P.front();
        }
    }
    return cnt;
}

void solve(ll N) {
    string S;
    cin >> S;
    ll SN = S.size();
    vector<vll> D(SN + 1);
    //-1:+, -2:*

    ll an = 0;
    ll cnt = 0;
    rep(i, SN) {
        if (S[i] == '(')cnt++;
        else if (S[i] == ')') {
            an += calc(D[cnt], N);
            ll res = eval(D[cnt]);
            D[cnt] = {};
            D[cnt - 1].push_back(res);
            cnt--;
        }
        else if (S[i] == '+') {
            D[cnt].push_back(-1);
        }
        else if (S[i] == '*') {
            D[cnt].push_back(-2);
        }
        else {
            D[cnt].push_back(S[i] - '0');
        }
    }
    an += calc(D[0], N);
    cout << an << endl;
}

int main() {

    ll N;
    while (cin >> N) {
        if (N == 0)return 0;
        solve(N);
    }
}
accuracy: 0.5
time_ms: 160
memory_kb: 150564
final_rank: 20

code_snippet: #include <iostream>
#include <vector>
#include <string>
#include <cassert>
using i64 = long long;

i64 ans = 0;

i64 rec(int &i, i64 N, std::string S)
{
    std::vector<std::vector<std::pair<i64, i64>>> v;
    v.push_back({});
    while (i < S.size())
    {
        if (S[i] == '(')
        {
            i += 1;
            i64 value = rec(i, N, S);
            assert(S[i] == ')');
            i += 1;
            if (value == 1 && v.back().size() > 0 && v.back().back().first == 1)
            {
                v.back().back().second += 1;
            }
            else
            {
                v.back().push_back({value, 1});
            }
        }
        else if (S[i] == ')')
        {
            break;
        }
        else if (S[i] == '+')
        {
            v.push_back({});
            i += 1;
        }
        else if (S[i] == '*')
        {
            i += 1;
        }
        else
        {
            int value = S[i] - '0';
            if (value == 1 && v.back().size() > 0 && v.back().back().first == 1)
            {
                v.back().back().second += 1;
            }
            else
            {
                v.back().push_back({value, 1});
            }
            i += 1;
        }
    }

    std::vector<i64> pi(v.size(), 0);
    i64 sum = 0;
    i64 ret = 0;
    std::vector<std::pair<int, int>> left;
    int li = 0;
    for (int x = 0; x < v.size(); x++)
    {
        i64 ret_pi = 1;
        for (int y = 0; y < v[x].size(); y++)
        {
            left.push_back({x, y});
            ret_pi *= v[x][y].first;
            ret_pi = std::min(N + 1, ret_pi);
            if (y == 0)
            {
                pi[x] += v[x][y].first;
                sum += pi[x];
            }
            else
            {
                sum -= pi[x];
                pi[x] *= v[x][y].first;
                sum += pi[x];
            }

            while (sum > N && li < left.size())
            {
                auto [i, j] = left[li];

                if (j + 1 == v[i].size())
                {
                    sum -= pi[i];
                    pi[i] = 0;
                }
                else
                {
                    sum -= pi[i];
                    pi[i] /= v[i][j].first;
                    sum += pi[i];
                }
                li++;
            }
            if (sum == N && li < left.size())
            {
                if (li + 1 == left.size())
                {
                    ans += v[x][y].second * (v[x][y].second + 1) / 2;
                }
                else
                {
                    auto [i, j] = left[li];
                    int add = 0;
                    if (v[i][j].first == 1 && j + 1 < v[i].size())
                    {
                        add += 1;
                    }
                    ans += (add + v[i][j].second) * v[x][y].second;
                }
            }
        }
        ret = std::min(N + 1, ret + ret_pi);
    }
    return ret;
}
bool solve()
{
    i64 N;
    std::cin >> N;
    if (N == 0)
        return false;
    std::string S;
    std::cin >> S;
    ans = 0;
    int i = 0;
    rec(i, N, S);
    std::cout << ans << std::endl;
    return true;
}

int main()
{
    while (solve())
        ;
}
accuracy: 1
time_ms: 400
memory_kb: 90808
final_rank: 11

code_snippet: #include <bits/stdc++.h>
//  03:05
constexpr long long INF = 1e18;
constexpr long long MAX = 1e9;

struct Data {
    std::vector<long long> digits;
    long long mul;
};

struct Parser {
    using CopyIter = std::string::const_iterator;
    using Iter = CopyIter&;
    std::string line;
    std::vector<std::vector<Data>> ans;

    Parser(const std::string& s): line(s) {}

    void skip(Iter it, char c) {
        assert(*it == c);
        ++it;
    }

    std::vector<std::vector<Data>> parse() {
        auto it = line.cbegin();
        expr(it);
        return ans;
    }

    long long expr(Iter it) {
        std::vector<Data> data;
        long long sum = 0;
        data.push_back(term(it));
        sum += data.back().mul;
        if (sum > MAX) {
            sum = INF;
        }
        while (it != line.end() && *it == '+') {
            skip(it, '+');
            data.push_back(term(it));
            sum += data.back().mul;
            if (sum > MAX) {
                sum = INF;
            }
        }
        ans.push_back(data);
        return sum;
    }

    Data term(Iter it) {
        Data data;
        data.digits.push_back(factor(it));
        while (it != line.end() && *it == '*') {
            skip(it, '*');
            data.digits.push_back(factor(it));
        }
        data.mul = 1;
        for (auto val: data.digits) {
            if (val == INF) {
                data.mul = INF;
                break;
            }
            data.mul *= val;
            if (data.mul > MAX) {
                data.mul = INF;
                break;
            }
        }
        return data;
    }

    long long factor(Iter it) {
        if (*it == '(') {
            skip(it, '(');
            auto res = expr(it);
            skip(it, ')');
            return res;
        } else {
            return number(it);
        }
    }

    long long number(Iter it) {
        char c = *it;
        assert(std::isdigit(c));
        skip(it, c);
        return c - '0';
    }
};

long long solve(long long n, const Data& data) {
    int r = 0;
    long long mul = 1;
    long long res = 0;
    std::vector<int> one(data.digits.size() + 1);
    for (int i = 0, now = 0; i <= (int)data.digits.size(); i++) {
        if (i < (int)data.digits.size() && data.digits[i] == 1) {
            now++;
        } else {
            one[i] = now;
            now = 0;
        }
    }
    for (int l = 0; l < (int)data.digits.size(); l++) {
        if (r < l) r = l;
        while (r < (int)data.digits.size()) {
            if (data.digits[r] == INF) break;
            if (mul * data.digits[r] > n) break;
            mul *= data.digits[r];
            r++;
        }
        assert(mul <= n);
        if (mul == n) {
            if (n != 1) {
                res += one[r] + 1;
            } else {
                res += r - l;
            }
        }
        if (l < r) {
            assert(mul % data.digits[l] == 0);
            mul /= data.digits[l];
        }
    }
    return res;
}

long long solve(long long n, const std::vector<Data>& data) {
    long long ans = 0;
    for (const auto& d: data) {
        ans += solve(n, d);
    }

    std::vector<std::map<long long, int>> left(data.size()), right(data.size());
    for (int i = 0; i < (int)data.size(); i++) {
        const auto& d = data[i];
        {
            long long mul = 1;
            for (int j = 0; j < (int)d.digits.size(); j++) {
                if (d.digits[j] == INF) break;
                mul *= d.digits[j];
                if (mul > MAX) break;
                left[i][mul]++;
            }
        }
        {
            long long mul = 1;
            for (int j = (int)d.digits.size() - 1; j >= 0; j--) {
                if (d.digits[j] == INF) break;
                mul *= d.digits[j];
                if (mul > MAX) break;
                right[i][-mul]++;
            }
        }
    }

    int r = 0;
    long long sum = 0;
    for (int l = 0; l < (int)data.size(); l++) {
        if (r <= l) r = l + 1;
        for (const auto& [v, c]: right[l]) {
            while (r < (int)data.size()) {
                if (sum + -v + data[r].mul > n) break;
                sum += data[r].mul;
                r++;
            }
            //std::cerr << -v << ' ' << n << ' ' << sum << std::endl;
            assert(-v > n || sum + -v <= n);
            if (sum != 0 && -v + sum == n) {
                ans += c * left[r - 1][data[r - 1].mul];
            } else if (r < (int)data.size()) {
                long long diff = n - sum - -v;
                ans += c * left[r][diff];
            }
        }
        if (l + 1 < r) {
            sum -= data[l + 1].mul;
        }
    }
    return ans;
}

int main() {
    while (true) {
        int n;
        std::cin >> n;
        if (n == 0) break;
        std::string line;
        std::cin >> line;
        Parser parser(line);
        // std::cerr << "start parse" << std::endl;
        auto data = parser.parse();

        // for (const auto& d: data) {
        //     std::cerr << " ----------- " << std::endl;
        //     for (const auto& dd: d) {
        //         std::cerr << dd.mul << std::endl;
        //     }
        // }

        // std::cerr << "end parse" << std::endl;
        long long ans = 0;
        for (const auto& d: data) {
            ans += solve(n, d);
        }
        std::cout << ans << std::endl;
    }
}
accuracy: 1
time_ms: 1260
memory_kb: 414728
final_rank: 17

code_snippet: #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	while (true) {
		int N;
		cin >> N;
		if (N == 0) {
			break;
		}
		string S;
		cin >> S;
		S = "(" + S + ")";
		vector<int> num;
		vector<char> op;
		vector<int> st;
		long long answer = 0;
		for (int i = 0; i < S.size(); i++) {
			if (S[i] == '(') {
				st.push_back(num.size());
			}
			if (S[i] == ')') {
				int cnt = 0;
				for (int j = st.back(); j < op.size(); j++) {
					if (op[j] == '+') {
						cnt += 1;
					}
				}
				vector<long long> seq1(cnt + 1, 1);
				vector<long long> seq2(cnt + 1, 1);
				seq1[0] = num[st.back()];
				seq2[0] = num[st.back()];
				long long val1 = num[st.back()];
				long long val2 = num[st.back()];
				int lpos1 = st.back(), rcur1 = 0, lcur1 = 0;
				int lpos2 = st.back(), rcur2 = 0, lcur2 = 0;
				int ND = max(N - 1, 1);
				for (int j = st.back(); j <= op.size(); j++) {
					while (val1 > N && lpos1 <= j) {
						val1 -= seq1[lcur1];
						seq1[lcur1] /= num[lpos1];
						val1 += seq1[lcur1];
						if (lpos1 == op.size() || op[lpos1] == '+') {
							lcur1 += 1;
							val1 -= 1;
						}
						lpos1 += 1;
					}
					while (val2 > ND && lpos2 <= j) {
						val2 -= seq2[lcur2];
						seq2[lcur2] /= num[lpos2];
						val2 += seq2[lcur2];
						if (lpos2 == op.size() || op[lpos2] == '+') {
							lcur2 += 1;
							val2 -= 1;
						}
						lpos2 += 1;
					}
					answer += j - lpos1 + 1;
					if (N >= 2) {
						answer -= j - lpos2 + 1;
					}
					if (j != op.size()) {
						if (op[j] == '+') {
							rcur1 += 1;
							rcur2 += 1;
							val1 += 1;
							val2 += 1;
						}
						val1 -= seq1[rcur1];
						val2 -= seq2[rcur2];
						seq1[rcur1] *= num[j + 1];
						seq2[rcur2] *= num[j + 1];
						val1 += seq1[rcur1];
						val2 += seq2[rcur2];
					}
				}
				num.resize(st.back());
				op.resize(st.back());
				if (lpos1 == st.back()) {
					num.push_back(val1);
				}
				else {
					num.push_back(N + 1);
				}
				st.pop_back();
			}
			if (S[i] == '+' || S[i] == '*') {
				op.push_back(S[i]);
			}
			if ('1' <= S[i] && S[i] <= '9') {
				num.push_back(int(S[i] - '0'));
			}
		}
		cout << answer << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 33200
final_rank: 3

code_snippet: #include <string.h>

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <chrono>
#include <ciso646>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define REP_OVERLOAD(arg1, arg2, arg3, arg4, NAME, ...) NAME
#define REP3(i, l, r, s)                                               \
    for (int i = int(l), rep3_r = int(r), rep3_s = int(s); i < rep3_r; \
         i += rep3_s)
#define REP2(i, l, r) REP3(i, l, r, 1)
#define REP1(i, n) REP2(i, 0, n)
#define rep(...) REP_OVERLOAD(__VA_ARGS__, REP3, REP2, REP1, )(__VA_ARGS__)
#define repin(i, l, r) for (int i = int(l), repin_r = int(r); i <= repin_r; ++i)

#define RREP_OVERLOAD(arg1, arg2, arg3, arg4, NAME, ...) NAME
#define RREP3(i, l, r, s)                                                      \
    for (int i = int(r) - 1, rrep3_l = int(l), rrep3_s = int(s); i >= rrep3_l; \
         i -= rrep3_s)
#define RREP2(i, l, r) RREP3(i, l, r, 1)
#define RREP1(i, n) RREP2(i, 0, n)
#define rrep(...) RREP_OVERLOAD(__VA_ARGS__, RREP3, RREP2, RREP1, )(__VA_ARGS__)
#define rrepin(i, l, r) \
    for (int i = int(r), rrepin_l = int(l); i >= rrepin_l; --i)


#include <algorithm>
#include <cassert>
#include <vector>

namespace rklib {

// a <- max(a, b)
template <class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

// a <- min(a, b)
template <class T>
bool chmin(T &a, const T &b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

// if a < 0: a <- b
// else: a <- min(a, b)
template <class T>
bool chmin_non_negative(T &a, const T &b) {
    if (a < 0 || a > b) {
        a = b;
        return true;
    }
    return false;
}

// floor(num / den)
template <class T>
T div_floor(T num, T den) {
    if (den < 0) num = -num, den = -den;
    return num >= 0 ? num / den : (num + 1) / den - 1;
}

// ceil(num / den)
template <class T>
T div_ceil(T num, T den) {
    if (den < 0) num = -num, den = -den;
    return num <= 0 ? num / den : (num - 1) / den + 1;
}

namespace internal {

template <class T>
T remainder_count(T r, T b, T m) {
    return r / m * b + std::min(b, r % m);
}

}  // namespace internal

// Number of integer x s.t.
// - x in [l, r)
// - x mod m in [a, b)
template <class T>
T remainder_count(T l, T r, T a, T b, T m) {
    assert(l >= 0);
    assert(m >= 1);

    if (l >= r || a >= b) return 0;
    if (m <= a || b < 0) return 0;
    chmax(a, T(0));
    chmin(b, m);

    auto res = internal::remainder_count(r, b, m);
    if (l >= 1) res -= internal::remainder_count(l, b, m);
    if (a >= 1) res -= internal::remainder_count(r, a, m);
    if (l >= 1 && a >= 1) res += internal::remainder_count(l, a, m);

    return res;
}

}  // namespace rklib


using namespace std;
using namespace rklib;

using lint = long long;
using pii = pair<int, int>;
using pll = pair<lint, lint>;

constexpr lint INF = 1e9 + 7;

int n;
string s;
int idx;
lint ans;

lint expr();
pair<lint, vector<lint>> term();
lint factor();

void solve(vector<vector<lint>> &a) {
    vector<pair<lint, int>> ps;
    vector<int> bucket;
    rep(i, a.size()) {
        for (int l = 0; l < int(a[i].size());) {
            if (a[i][l] != 1) {
                ps.emplace_back(a[i][l], 1);
                bucket.push_back(i);
                ++l;
                continue;
            }
            int r = l;
            while (r < int(a[i].size()) && a[i][r] == 1) ++r;
            ps.emplace_back(1, r - l);
            bucket.push_back(i);
            l = r;
        }
    }
    // for (auto p : ps) printf("(%lld, %d) ", p.first, p.second);
    // puts("");
    // cout << "bucket: ";
    // for (auto x : bucket) printf("%d ", x);
    // puts("");

    deque<tuple<lint, int, int>> dq;  // (val, num, bucket)
    int r = 0;
    lint tmp = 0;
    vector<lint> prods(bucket.size(), 0);
    vector<int> cnt(bucket.size(), 0);
    rep(l, ps.size()) {
        // extend
        while (r < int(ps.size()) && tmp < n) {
            auto [val, num] = ps[r];
            auto b = bucket[r];
            if (cnt[b] == 0) {
                prods[b] = val;
                tmp += val;
                // chmin(tmp, INF);
                ++cnt[b];
            } else {
                tmp -= prods[b];
                prods[b] *= val;
                tmp += prods[b];
                // chmin(tmp, INF);
                ++cnt[b];
            }
            dq.emplace_back(val, num, b);
            ++r;
        }
        if (!dq.empty() && r < int(ps.size()) && ps[r].first == 1 &&
            get<2>(dq.back()) == bucket[r]) {
            dq.emplace_back(1, ps[r].second, bucket[r]);
            ++cnt[bucket[r]];
            ++r;
        }

        if (tmp == n) {
            if (dq.size() == 1) {
                auto [val, num, b] = dq.front();
                // cout << val << " " << num << " " << b << endl;
                if (val == 1) {
                    ans += lint(num) * (num + 1) / 2;
                } else {
                    ++ans;
                }
            } else {
                auto [fv, fn, fb] = dq.front();
                auto [bv, bn, bb] = dq.back();
                // cout << tmp << endl;
                // cout << fv << " " << fn << " " << fb << endl;
                // cout << bv << " " << bn << " " << bb << endl;

                lint a = 1;
                if (fv == 1) a = fn;
                lint b = 1;
                if (bv == 1) b = (prods[bb] == 1 ? bn : bn + 1);
                ans += a * b;

                // cout << a << " " << b << endl;
            }
        }

        // cout << l << " " << r << " " << tmp << endl;

        // shrink
        auto [val, num] = ps[l];
        auto b = bucket[l];
        --cnt[b];
        if (cnt[b] == 0) {
            tmp -= prods[b];
            prods[b] = 0;
        } else {
            tmp -= prods[b];
            prods[b] /= val;
            tmp += prods[b];
        }
        dq.pop_front();
    }
    // cout << ans << endl;
}

lint expr() {
    vector<vector<lint>> a;
    lint res = 0;

    {
        auto [val, v] = term();
        res = val;
        a.push_back(v);
    }
    while (idx < int(s.size()) & s[idx] == '+') {
        ++idx;
        auto [val, v] = term();
        res = min(INF, res + val);
        a.push_back(v);
    }

    // cout << "val: " << res << endl;
    // for (auto v : a) {
    //     for (auto x : v) cout << x << " ";
    //     cout << endl;
    // }

    solve(a);

    return res;
}
pair<lint, vector<lint>> term() {
    lint res = 1;
    vector<lint> a;

    {
        auto val = factor();
        res = min(INF, res * val);
        a.push_back(val);
    }
    while (idx < int(s.size()) & s[idx] == '*') {
        ++idx;
        auto val = factor();
        res = min(INF, res * val);
        a.push_back(val);
    }

    return {res, a};
}
lint factor() {
    if (isdigit(s[idx])) {
        ++idx;
        return s[idx - 1] - '0';
    }
    ++idx;
    auto res = expr();
    ++idx;
    return res;
}

int main() {
    while (true) {
        cin >> n;
        if (n == 0) break;
        cin >> s;

        idx = 0;
        ans = 0;
        expr();

        cout << ans << "\n";
    }
}
accuracy: 1
time_ms: 250
memory_kb: 109220
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL << 30;
#define rep(i, n) for(int i=0;i<n;i++)

ll solve(long long n, string s){
    int m = s.length();

    vector<int> lr(m, 0);
    iota(lr.begin(), lr.end(), 0);
    {
        stack<int> st;
        rep(i, m) {
            if(s[i] == '(') {
                st.push(i);
            } else if(s[i] == ')') {
                swap(lr[st.top()], lr[i]);
                st.pop();
            } 
        }
    }

    ll ans = 0;

    auto calc2 = [&](vector<ll> &v) -> void {
        int k = v.size();
        assert(k & 1);
        vector<ll> ones(k + 2, 0);
        for(int i = k - 3; i >= 0; i -= 2) {
            if(v[i] == 1 and v[i + 1] == 1) {
                ones[i] = ones[i + 2] + 1;
            } 
        }
        ll sum = v[0];
        deque<ll> dq;
        dq.push_back(v[0]);
        if(v[0] == n) ans ++;

        int j = 0;
        for(int i = 2; i < k; i += 2) {
            if(v[i - 1]) {
                sum -= dq.back();
                dq.back() *= v[i];
                sum += dq.back();
            } else {
                dq.push_back(v[i]);
                sum += v[i];
            }
            if(sum == n) {
                if(n == 1) {
                    ans += ((ll)(i - j) >> 1LL) + 1;
                    continue;
                }
                ans += ones[j] + 1;
                continue;
            } 

            while(sum > n) {
                if(v[j + 1]) {
                    assert(dq.front() % v[j] == 0);
                    sum -= dq.front();
                    dq.front() /= v[j];
                    sum += dq.front();
                } else {
                    sum -= dq.front();
                    dq.pop_front();
                }
                j += 2;
            }
            if(sum == n) {
                if(n == 1) {
                    ans += ((ll)(i - j) >> 1LL) + 1;
                    continue;
                }
                ans += ones[j] + 1;
            }
        }
    };

    auto calc = [&](vector<ll> &v) -> void {
        vector<ll> tmp;
        int k = v.size();
        assert(k & 1);
        for(ll i = 0; i < k; i ++) {
            if(i & 1) {
                tmp.push_back(v[i]);
            } else {
                if(v[i] > n) {
                    if(tmp.empty());
                    else {
                        tmp.resize(tmp.size() - 1);
                        calc2(tmp);
                        tmp.clear();
                    }
                    i ++;
                    continue;
                } 
                tmp.push_back(v[i]);
            }
        }
        if(!tmp.empty()) calc2(tmp);
    };

    auto dfs = [&](auto dfs, int le, int ri) -> ll { // 合計を返す
        vector<ll> v;
        ll sum = 0, now = 0;
        bool mode = 0; // 0 add, 1 mul
        for(int i = le; i < ri; i ++) {
            ll num = 0;
            if(s[i] == '(') {
                v.push_back(dfs(dfs, i + 1, lr[i]));
                num = v.back();
            } else if(s[i] == '+') {
                v.push_back(0);
                mode = 0;
                sum += now;
                if(sum > n) sum = INF;
                now = 0;
                continue;
            } else if(s[i] == '*') {
                v.push_back(1);
                mode = 1;
                continue;
            } else {
                num = s[i] - '0';
                v.push_back(num);
            }

            if(sum + now > n) {
                sum = INF;
                now = 0;
                i = lr[i];
                continue;
            }

            if(le == i) {
                now = num;
            } else if(mode) {
                now *= num;
            } else {
                now += num;
            }
            if(sum + now > n) {
                sum = INF;
                now = 0;
            }
            i = lr[i];
        }
        if(sum != INF) sum += now;
        if(sum > n) sum = INF; 
        calc(v);
        return sum;
    };

    dfs(dfs, 0, m);
    return ans;
}
int main(){
    long long n;
    cin >> n;
    while(n != 0LL){
        string s;
        cin >> s;
        cout << solve(n, s) << endl;
        cin >> n;
    }
}
accuracy: 1
time_ms: 130
memory_kb: 81764
final_rank: 6

code_snippet: #include <bits/stdc++.h>

using namespace std;

using ll = long long;
void solve(ll n, string s) {
	ll ans = 0;
	int t = 0;
	auto dfs = [&](auto f) -> ll {
		ll cur = 1;
		ll all = 0;
		bool inf = false;
		bool all_inf = false;
		vector<ll> V;
		while(t < s.size()) {
			if(s[t] >= '0' && s[t] <= '9') {
				V.push_back(s[t] - '0');
				cur *= s[t] - '0';
				if(cur > n) inf = true;
			} else if(s[t] == '(') {
				t++;
				ll inner = f(f);
				if(inner < 0) {
					inf = true;
				}
				V.push_back(inner);
				cur *= inner;
				if(cur > n) inf = true;
			} else if(s[t] == '*') {
				V.push_back(0);
			} else if(s[t] == '+') {
				if(inf) all_inf = true;
				inf = false;
				all += cur;
				if(all > n) all_inf = true;
				cur = 1;
				V.push_back(1);
			} else {
				break;
			}
			t++;
		}
		all += cur;
		if(all > n) all_inf = true;
		if(inf) all_inf = true;
		cur = 1;
		int i = 0;
		int j = 0;
		deque<ll> DI;
		deque<ll> DJ;
		ll curI = V[0];
		ll curJ = V[0];
		DI.push_back(V[0]);
		DJ.push_back(V[0]);
		bool infI = false;
		bool infJ = false;
		if(V[0] == -1) {
			curI = 0;
			curJ = 0;
			DI.front() = 1;
			DJ.front() = 1;
			infI = true;
			infJ = true;
		}
		for(int l = 0; l < V.size(); l += 2) {
			if(l > i) {
				i = l;
				while(!DI.empty()) DI.pop_front();
				if(V[l] == -1) {
					infI = true;
					DI.push_front(1);
					curI = 0;
				} else {
					curI = V[l];
					DI.push_back(V[l]);
					infI = false;
				}
			}
			if(l > j) {
				j = l;
				while(!DJ.empty()) DJ.pop_front();
				if(V[l] == -1) {
					infJ = true;
					DJ.push_front(1);
					curJ = 0;
				} else {
					curJ = V[l];
					DJ.push_back(V[l]);
					infJ = false;
				}
			}
			while(!infI && curI < n && i + 1 < V.size()) {
				int op = V[i + 1];	// 0:*, 1:+
				ll a = V[i + 2];
				if(a == -1) {
					infI = true;
				} else if(op == 1) {
					curI += a;
					DI.push_back(a);
				} else {
					curI -= DI.back();
					DI.back() *= a;
					curI += DI.back();
				}
				i += 2;
			}
			while(!infJ && curJ < n + 1
				  && j + 1 < V.size()) {
				int op = V[j + 1];
				ll a = V[j + 2];
				if(a == -1) {
					infJ = true;
				} else if(op == 1) {
					curJ += a;
					DJ.push_back(a);
				} else {
					curJ -= DJ.back();
					DJ.back() *= a;
					curJ += DJ.back();
				}
				j += 2;
			}
			if(!infI && curI < n && i < V.size()) i += 2;
			if(!infJ && curJ < n + 1 && j < V.size())
				j += 2;

			ans += (j - i) / 2;
			if(l + 1 >= V.size()) break;
			int op = V[l + 1];
			int a = V[l];
			if(a == -1) {
				infI = false;
				infJ = false;
			} else if(op == 1) {
				int si = DI.size();
				curI -= DI.front();
				DI.pop_front();
				curJ -= DJ.front();
				DJ.pop_front();
			} else {
				curI -= DI.front();
				DI.front() /= a;
				curI += DI.front();
				curJ -= DJ.front();
				DJ.front() /= a;
				curJ += DJ.front();
			}
		}
		if(all_inf)
			return -1;
		else
			return all;
	};
	dfs(dfs);
	cout << ans << endl;
}
int main() {
	int n;
	cin >> n;
	while(n != 0) {
		string s;
		cin >> s;
		solve(n, s);
		cin >> n;
	}
}
accuracy: 1
time_ms: 100
memory_kb: 42352
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
    while(1) {
        ll n; cin >> n;
        if(!n) break;
        string s; cin >> s;
        s = '(' + s + ')';
        int len = s.size();
        auto solve = [&](ll target) { // target以下が何通り
            if(target == 0) return 0LL;
            stack<vector<vector<int>>> stk; // カッコのレベルごとの積項の列
            ll ans = 0;
            for(int i = 0; i < len; i++) {
                if(s[i] == '(') {
                    stk.emplace(vector<vector<int>>(1));
                } else if(s[i] == ')') {
                    {
                        // 1つの積項の中で完結
                        for(auto& term : stk.top()) {
                            int r = 0;
                            ll cur = 1;
                            term.push_back((ll)2e9); // 番兵
                            for(int l = 0; l < (int)term.size()-1; cur /= term[l++]) { // [l,r)の積 <= target
                                if(l > r) {
                                    r = l;
                                    cur = 1;
                                }
                                while(cur <= target) cur *= term[r++];
                                ans += max(0, r - l - 1);
                            }
                            term.pop_back();
                        }
                    }
                    stk.top().push_back(vector<int>(1, (ll)2e9)); // 番兵
                    vector<vector<ll>> factor_prod_l; // 積項内の因数の左からの累積
                    vector<vector<ll>> factor_prod_r; // 積項内の因数の右からの累積
                    for(auto& term : stk.top()) {
                        int m = term.size();
                        factor_prod_l.emplace_back(vector<ll>(m+1));
                        factor_prod_r.emplace_back(vector<ll>(m+1));
                        factor_prod_l.back()[0] = factor_prod_r.back()[m] = 1;
                        for(int fi = 0; fi < m; fi++) {
                            factor_prod_l.back()[fi+1] = min((ll)2e9, factor_prod_l.back()[fi] * term[fi]);
                        }
                        for(int fi = m-1; fi >= 0; fi--) {
                            factor_prod_r.back()[fi] = min((ll)2e9, factor_prod_r.back()[fi+1] * term[fi]);
                        }
                    }
                    vector<int> factor_cnt_sum; // 積項内の因数の個数の累積和
                    vector<ll> factor_prod_sum; // 積項の内の累積和
                    factor_cnt_sum.emplace_back(0);
                    factor_prod_sum.emplace_back(0);
                    for(int ti = 0; ti < (int)stk.top().size(); ti++) {
                        factor_cnt_sum.emplace_back(factor_cnt_sum.back() + stk.top()[ti].size());
                        factor_prod_sum.emplace_back(factor_prod_sum.back() + factor_prod_l[ti].back());
                    }
                    stk.top().pop_back();
                    {
                        auto val = [&](int lti, int lfi, int rti, int rfi) {
                            assert(lti < rti);
                            return factor_prod_r[lti][lfi] + (factor_prod_sum[rti] - factor_prod_sum[lti+1]) + factor_prod_l[rti][rfi];
                        };
                        // 2つ以上の積項
                        int rti = 1, rfi = 1;
                        for(int ti = 0; ti < (int)stk.top().size(); ti++) {
                            for(int fi = 0; fi < (int)stk.top()[ti].size(); fi++) {
                                if(rti <= ti) {
                                    rti = ti+1;
                                    rfi = 1;
                                }
                                while(val(ti, fi, rti, rfi) <= target) {
                                    if(rfi == (int)stk.top()[rti].size()) {
                                        rti++;
                                        rfi = 1;
                                    } else {
                                        rfi++;
                                    }
                                }
                                ans += max(0, factor_cnt_sum[rti] + rfi - factor_cnt_sum[ti+1] - 1);
                            }
                        }
                    }
                    stk.pop();
                    if(!stk.empty()) {
                        factor_prod_sum.pop_back();
                        // 式全体の値をカッコの外に置く
                        stk.top().back().emplace_back(min((ll)2e9, factor_prod_sum.back()));
                    }
                } else if(s[i] == '*');
                else if(s[i] == '+') {
                    stk.top().emplace_back();
                } else {
                    stk.top().back().emplace_back(s[i] - '0');
                }
            }
            return ans;
        };
        cout << solve(n) - solve(n-1) << '\n';
    }
}
accuracy: 1
time_ms: 800
memory_kb: 195040
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
    while(1) {
        ll n; cin >> n;
        if(!n) break;
        string s; cin >> s;
        s = '(' + s + ')';
        int len = s.size();
        auto solve = [&](ll target) { // target以下が何通り
            /* cerr << target << '\n'; */
            if(target == 0) return 0LL;
            stack<vector<vector<int>>> stk; // カッコのレベルごとの積項の列
            ll ans = 0;
            for(int i = 0; i < len; i++) {
                /* cerr << i << ' ' << ans << endl; */
                if(s[i] == '(') {
                    stk.emplace(vector<vector<int>>(1));
                } else if(s[i] == ')') {
                    /* cerr << '!' << ans << '\n'; */
                    {
                        // 1つの積項の中で完結
                        for(auto& term : stk.top()) {
                            /* cerr << term.size() << '\n'; */
                            int r = 0;
                            ll cur = 1;
                            term.push_back((ll)2e9); // 番兵
                            for(int l = 0; l < (int)term.size()-1; cur /= term[l++]) { // [l,r)の積 <= target
                                if(l > r) {
                                    r = l;
                                    cur = 1;
                                }
                                while(cur <= target) cur *= term[r++];
                                /* cerr << l << ' ' << r << ' ' << cur << '\n'; */
                                ans += max(0, r - l - 1);
                            }
                            term.pop_back();
                        }
                    }
                    /* cerr << '@' << ans << '\n'; */
                    stk.top().push_back(vector<int>(1, (ll)2e9)); // 番兵
                    vector<vector<ll>> factor_prod_l; // 積項内の因数の左からの累積
                    vector<vector<ll>> factor_prod_r; // 積項内の因数の右からの累積
                    for(auto& term : stk.top()) {
                        int m = term.size();
                        factor_prod_l.emplace_back(vector<ll>(m+1));
                        factor_prod_r.emplace_back(vector<ll>(m+1));
                        factor_prod_l.back()[0] = factor_prod_r.back()[m] = 1;
                        for(int fi = 0; fi < m; fi++) {
                            factor_prod_l.back()[fi+1] = min((ll)2e9, factor_prod_l.back()[fi] * term[fi]);
                        }
                        for(int fi = m-1; fi >= 0; fi--) {
                            factor_prod_r.back()[fi] = min((ll)2e9, factor_prod_r.back()[fi+1] * term[fi]);
                        }
                    }
                    vector<int> factor_cnt_sum; // 積項内の因数の個数の累積和
                    vector<ll> factor_prod_sum; // 積項の内の累積和
                    factor_cnt_sum.emplace_back(0);
                    factor_prod_sum.emplace_back(0);
                    for(int ti = 0; ti < (int)stk.top().size(); ti++) {
                        factor_cnt_sum.emplace_back(factor_cnt_sum.back() + stk.top()[ti].size());
                        factor_prod_sum.emplace_back(factor_prod_sum.back() + factor_prod_l[ti].back());
                    }
                    stk.top().pop_back();
                    {
                        auto val = [&](int lti, int lfi, int rti, int rfi) {
                            assert(lti < rti);
                            return factor_prod_r[lti][lfi] + (factor_prod_sum[rti] - factor_prod_sum[lti+1]) + factor_prod_l[rti][rfi];
                        };
                        // 2つ以上の積項
                        int rti = 1, rfi = 1;
                        for(int ti = 0; ti < (int)stk.top().size(); ti++) {
                            for(int fi = 0; fi < (int)stk.top()[ti].size(); fi++) {
                                if(rti <= ti) {
                                    rti = ti+1;
                                    rfi = 1;
                                }
                                while(val(ti, fi, rti, rfi) <= target) {
                                    if(rfi == (int)stk.top()[rti].size()) {
                                        rti++;
                                        rfi = 1;
                                    } else {
                                        rfi++;
                                    }
                                }
                                ans += max(0, factor_cnt_sum[rti] + rfi - factor_cnt_sum[ti+1] - 1);
                            }
                        }
                    }
                    /* cerr << '#' << ans << '\n'; */
                    ll value = 0; // 式全体の値
                    for(int ti = 0; ti < (int)stk.top().size(); ti++) {
                        value = min((ll)2e9, value + factor_prod_l[ti].back());
                    }
                    /* cerr << "val" << value << '\n'; */
                    stk.pop();
                    if(!stk.empty()) {
                        stk.top().back().emplace_back(value);
                    }
                } else if(s[i] == '*');
                else if(s[i] == '+') {
                    stk.top().emplace_back();
                } else {
                    stk.top().back().emplace_back(s[i] - '0');
                }
            }
            return ans;
        };
        cout << solve(n) - solve(n-1) << '\n';
    }
}
accuracy: 1
time_ms: 820
memory_kb: 193832
final_rank: 16