Problem:
6÷2(1+2)
English text is not available in this practice contest.
数学科の学生であるきたまさ君は，数学はとても得意なのだが算数はあまり得意ではない．
特に演算子の優先順位が苦手で，
カッコの中を先に計算するというのはわかるのだが， "+" と "*" のどちらを優先したら良いかとか複数の演算子が並んでいるときに左から計算したら良いのか右から計算したら良いのか覚えておらず，
その時の気分で好きな順番で計算をしている．例えば，"1*1-1+1"という数式を前から"((1*1)-1)+1"という順番で計算する場合もあれば，真ん中から"(1*(1-1))+1"という順番で計算する場合さえある．
また，分数や小数も苦手で，割り算では常に絶対値の小さい方に丸め，小数部を切り捨てて整数にしてしまう．
割る数がゼロであった場合には，きたまさ君はどこかで間違えたと思ってもう一度最初から計算しなおすことにしている．
きたまさ君はどんな順番で計算しても最終的な計算結果は同じになると主張しているので，あなたにはそれが間違いであると示すために，与えられた数式に対して
きたまさ君の計算結果が何通りあり得るかを求めるプログラムを書いて欲しい．
ただし，演算の順番が異なっていても，最終的な答えが同じならば一つと数えるものとし，
また，与えられる数式は，少なくとも一つはゼロ割が発生しない演算順序が存在し，いかなる演算順序で計算した場合でも，計算結果と途中で現れる数の絶対値は常に 10
9
以下であることが保証されている．
Input
入力はひとつ以上の行からなり，入力の各行は数式ひとつを含む．数式の文法は以下の BNF で与えられる．
<expr> ::= <num>
        | "(" <expr> ")"
        | <expr> "+" <expr>
        | <expr> "-" <expr>
        | <expr> "*" <expr>
        | <expr> "/" <expr>
<num> ::= <digit> | <num> <digit>
<digit> ::= "0" | "1" | "2" | "3" | "4"
          | "5" | "6" | "7" | "8" | "9"
すべての数式はこの構文規則に従う．また，入力行の長さは 200 文字を超えない．ひとつの数式が含む演算子 ( "+" , "-" , "*" , "/" ) の数は 10 個を超えない．
入力の終わりは "#" ひとつだけからなる行によって示される．
Output
それぞれの数式について，きたまさ君の計算結果が何通りあり得るかを出力せよ．出力は数式ひとつごとに 1 行とする．
Sample Input
6/2*(1+2)
1-1-1
(1-1-1)/2
#
Output for the Sample Input
2
2
1

Submitted solutions:

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

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

vector<vi> G;
vector<pair<int, char>> val_op;
int tidx = 0;

// 木を構成
int number(const string &s, int &i) {
  int ret = 0;
  while (i < sz(s) && isdigit(s[i])) {
    ret = 10 * ret + (s[i] - '0');
    i++;
  }
  val_op.emplace_back(ret, 'd');
  G.push_back({});
  tidx++;
  return tidx - 1;
}
int expr(const string &s, int &i) {
  val_op.emplace_back(-1, 'r');  //()をあらわす
  G.push_back({});
  int p = tidx;
  tidx++;
  vi c;  // 子 演算子,expr
  while (i < sz(s)) {
    if (s[i] == '(') {
      assert(s[i] == '(');
      i++;  // (
      int cp = expr(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
      assert(s[i] == ')');
      i++;  // )
    } else {
      assert(isdigit(s[i]));
      int cp = number(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
    }
    if (i >= sz(s)) return p;
    if (s[i] == ')') return p;
    bool f = 0;
    for (auto chara : "+-*/")
      if (chara == s[i]) f = 1;
    assert(f);
    if (!f) return p;
    int opp = tidx;
    G.push_back({});
    val_op.emplace_back(-1, s[i]);
    tidx++;
    G[p].push_back(opp);
    G[opp].push_back(p);
    i++;
  }
  return p;
}

bool isop(char c) {
  bool f = 0;
  for (char cc : "+-*/")
    if (cc == c) f = 1;
  return f;
}
bool solve() {
  tidx = 0;
  G.clear();
  val_op.clear();
  string s;
  cin >> s;
  if (s == "#") return 0;
  int root = 0;
  {
    int i = 0;
    root = expr(s, i);
  }

  vector<set<int>> st(tidx);
  auto dfs = [&](auto dfs, int v, int p) -> char {
    if (val_op[v].second == 'r') {
      vector<char> op;
      vector<int> sidx;
      for (auto to : G[v]) {
        if (to == p) continue;
        if (val_op[to].second != 'r' && val_op[to].second != 'd') {
          op.push_back(val_op[to].second);
        } else {
          dfs(dfs, to, v);
          sidx.push_back(to);
          assert(sz(st[to]) > 0);
        }
      }
      assert(sz(op) + 1 == sz(sidx));
      vector<vi> vv;
      {
        vi v;
        auto f1 = [&](auto f1, int i) -> void {
          if (i >= sz(sidx)) {
            vv.push_back(v);
            return;
          }
          for (auto x : st[sidx[i]]) {
            v.push_back(x);
            f1(f1, i + 1);
            v.pop_back();
          }
        };
        f1(f1, 0);
      }
      vi order(sz(op));
      iota(all(order), 0);
      do {
        for (auto vect : vv) {
        bool f=1;
          auto tmp=vect;
          vi tmp_c(sz(sidx), 1);  // つかえるか
        //   cout<<endl;
          rep(i, 0, sz(op)) {
            // for(auto x:tmp)cout<<x<<" ";cout<<endl;
            int j = order[i];
            int l = j, r = j + 1;
            while (l >= 0 && !tmp_c[l]) l--;
            while (r < sz(sidx) && !tmp_c[r]) r++;
            assert(l >= 0);
            assert(r < sz(sidx));
            assert(isop(op[i]));
            assert(tmp_c[l]);
            assert(tmp_c[r]);
            int tl = tmp[l];
            int tr = tmp[r];
            if (op[j] == '+') tmp[l] = tl + tr;
            if (op[j] == '-') tmp[l] = tl - tr;
            if (op[j] == '*') tmp[l] = tl * tr;
            if (op[j] == '/'){
                if(tr==0){
                    f=0;
                    break;
                }
                tmp[l] = tl / tr;
            }
            tmp_c[r] = 0;
            tmp[r]=0;
          }
          if(f)st[v].insert(tmp[0]);
        }
      } while (next_permutation(all(order)));

      //assert(sz(st[v]) > 0);
    } else if (val_op[v].second == 'd') {
      st[v].insert(val_op[v].first);
      assert(sz(st[v]) > 0);
    }
    return val_op[v].second;
  };
  dfs(dfs, root, -1);
  cout << sz(st[root]) << endl;
  return 1;
}
accuracy: 1
time_ms: 390
memory_kb: 3584
final_rank: 3

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

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

vector<vi> G;
vector<pair<int, char>> val_op;
int tidx = 0;

// 木を構成
int number(const string &s, int &i) {
  int ret = 0;
  while (i < sz(s) && isdigit(s[i])) {
    ret = 10 * ret + (s[i] - '0');
    i++;
  }
  val_op.emplace_back(ret, 'd');
  G.push_back({});
  tidx++;
  return tidx - 1;
}
int expr(const string &s, int &i) {
  val_op.emplace_back(-1, 'r');  //()をあらわす
  G.push_back({});
  int p = tidx;
  tidx++;
  vi c;  // 子 演算子,expr
  while (i < sz(s)) {
    if (s[i] == '(') {
      assert(s[i] == '(');
      i++;  // (
      int cp = expr(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
      assert(s[i] == ')');
      i++;  // )
    } else {
      assert(isdigit(s[i]));
      int cp = number(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
    }
    if (i >= sz(s)) return p;
    if (s[i] == ')') return p;
    bool f = 0;
    for (auto chara : "+-*/")
      if (chara == s[i]) f = 1;
    assert(f);
    if (!f) return p;
    int opp = tidx;
    G.push_back({});
    val_op.emplace_back(-1, s[i]);
    tidx++;
    G[p].push_back(opp);
    G[opp].push_back(p);
    i++;
  }
  return p;
}

bool isop(char c) {
  bool f = 0;
  for (char cc : "+-*/")
    if (cc == c) f = 1;
  return f;
}
bool solve() {
  tidx = 0;
  G.clear();
  val_op.clear();
  string s;
  cin >> s;
  if (s == "#") return 0;
  int root = 0;
  {
    int i = 0;
    root = expr(s, i);
  }

  vector<set<int>> st(tidx);
  auto dfs = [&](auto dfs, int v, int p) -> char {
    if (val_op[v].second == 'r') {
      vector<char> op;
      vector<int> sidx;
      for (auto to : G[v]) {
        if (to == p) continue;
        if (val_op[to].second != 'r' && val_op[to].second != 'd') {
          op.push_back(val_op[to].second);
        } else {
          dfs(dfs, to, v);
          sidx.push_back(to);
          assert(sz(st[to]) > 0);
        }
      }
      assert(sz(op) + 1 == sz(sidx));
      vector<vi> vv;
      {
        vi v;
        auto f1 = [&](auto f1, int i) -> void {
          if (i >= sz(sidx)) {
            vv.push_back(v);
            return;
          }
          for (auto x : st[sidx[i]]) {
            v.push_back(x);
            f1(f1, i + 1);
            v.pop_back();
          }
        };
        f1(f1, 0);
      }
      vi order(sz(op));
      iota(all(order), 0);
      do {
        bool f=1;
        for (auto vect : vv) {
          auto tmp=vect;
          vi tmp_c(sz(sidx), 1);  // つかえるか
        //   cout<<endl;
          rep(i, 0, sz(op)) {
            // for(auto x:tmp)cout<<x<<" ";cout<<endl;
            int j = order[i];
            int l = j, r = j + 1;
            while (l >= 0 && !tmp_c[l]) l--;
            while (r < sz(sidx) && !tmp_c[r]) r++;
            assert(l >= 0);
            assert(r < sz(sidx));
            assert(isop(op[i]));
            assert(tmp_c[l]);
            assert(tmp_c[r]);
            int tl = tmp[l];
            int tr = tmp[r];
            if (op[j] == '+') tmp[l] = tl + tr;
            if (op[j] == '-') tmp[l] = tl - tr;
            if (op[j] == '*') tmp[l] = tl * tr;
            if (op[j] == '/'){
                if(tr==0){
                    f=0;
                    break;
                }
                tmp[l] = tl / tr;
            }
            tmp_c[r] = 0;
            tmp[r]=0;
          }
                    //   for(auto x:tmp)cout<<x<<" ";cout<<endl;

          if(f)st[v].insert(tmp[0]);
        }
      } while (next_permutation(all(order)));

      //assert(sz(st[v]) > 0);
    } else if (val_op[v].second == 'd') {
      st[v].insert(val_op[v].first);
      assert(sz(st[v]) > 0);
    }
    return val_op[v].second;
  };
  dfs(dfs, root, -1);
  cout << sz(st[root]) << endl;
  return 1;
}
accuracy: 0.5
time_ms: 400
memory_kb: 3584
final_rank: 19

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

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

vector<vi> G;
vector<pair<int, char>> val_op;
int tidx = 0;

// 木を構成
int number(const string &s, int &i) {
  int ret = 0;
  while (i < sz(s) && isdigit(s[i])) {
    ret = 10 * ret + (s[i] - '0');
    i++;
  }
  val_op.emplace_back(ret, 'd');
  G.push_back({});
  tidx++;
  return tidx - 1;
}
int expr(const string &s, int &i) {
  val_op.emplace_back(-1, 'r');  //()をあらわす
  G.push_back({});
  int p = tidx;
  tidx++;
  vi c;  // 子 演算子,expr
  while (i < sz(s)) {
    if (s[i] == '(') {
      assert(s[i] == '(');
      i++;  // (
      int cp = expr(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
      assert(s[i] == ')');
      i++;  // )
    } else {
      assert(isdigit(s[i]));
      int cp = number(s, i);
      G[p].push_back(cp);
      G[cp].push_back(p);
    }
    if (i >= sz(s)) return p;
    if (s[i] == ')') return p;
    bool f = 0;
    for (auto chara : "+-*/")
      if (chara == s[i]) f = 1;
    assert(f);
    if (!f) return p;
    int opp = tidx;
    G.push_back({});
    val_op.emplace_back(-1, s[i]);
    tidx++;
    G[p].push_back(opp);
    G[opp].push_back(p);
    i++;
  }
  return p;
}

bool isop(char c) {
  bool f = 0;
  for (char cc : "+-*/")
    if (cc == c) f = 1;
  return f;
}
bool solve() {
  tidx = 0;
  G.clear();
  val_op.clear();
  string s;
  cin >> s;
  if (s == "#") return 0;
  int root = 0;
  {
    int i = 0;
    root = expr(s, i);
  }

  vector<set<int>> st(tidx);
  auto dfs = [&](auto dfs, int v, int p) -> char {
    if (val_op[v].second == 'r') {
      vector<char> op;
      vector<int> sidx;
      for (auto to : G[v]) {
        if (to == p) continue;
        if (val_op[to].second != 'r' && val_op[to].second != 'd') {
          op.push_back(val_op[to].second);
        } else {
          dfs(dfs, to, v);
          sidx.push_back(to);
          assert(sz(st[to]) > 0);
        }
      }
      assert(sz(op) + 1 == sz(sidx));
      vector<vi> vv;
      {
        vi v;
        auto f1 = [&](auto f1, int i) -> void {
          if (i >= sz(sidx)) {
            vv.push_back(v);
            return;
          }
          for (auto x : st[sidx[i]]) {
            v.push_back(x);
            f1(f1, i + 1);
            v.pop_back();
          }
        };
        f1(f1, 0);
      }
      vi order(sz(op));
      iota(all(order), 0);
      do {
        bool f=1;
        for (auto tmp : vv) {
          vi tmp_c(sz(sidx), 1);  // つかえるか
          rep(i, 0, sz(op)) {
            int j = order[i];
            int l = j, r = j + 1;
            while (l >= 0 && !tmp_c[l]) l--;
            while (r < sz(sidx) && !tmp_c[r]) r++;
            assert(l >= 0);
            assert(r < sz(sidx));
            assert(isop(op[i]));
            assert(tmp_c[l]);
            assert(tmp_c[r]);
            int tl = tmp[l];
            int tr = tmp[r];
            if (op[j] == '+') tmp[l] = tl + tr;
            if (op[j] == '-') tmp[l] = tl - tr;
            if (op[j] == '*') tmp[l] = tl * tr;
            if (op[j] == '/'){
                if(tr==0){
                    f=0;
                    break;
                }
                tmp[l] = tl / tr;
            }
            tmp_c[r] = 0;
            tmp[r]=0;
          }
          if(f)st[v].insert(tmp[0]);
        }
      } while (next_permutation(all(order)));

      //assert(sz(st[v]) > 0);
    } else if (val_op[v].second == 'd') {
      st[v].insert(val_op[v].first);
      assert(sz(st[v]) > 0);
    }
    return val_op[v].second;
  };
  dfs(dfs, root, -1);
  cout << sz(st[root]) << endl;
  return 1;
}
accuracy: 0.5
time_ms: 340
memory_kb: 3712
final_rank: 20

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

#include <atcoder/all>
using namespace atcoder;

using ll = long long;
using mint = modint998244353;

bool is_operator(char c) {
    return (c == '+' || c == '-' || c == '/' || c == '*');
}

ll safe_div(ll &x, ll &y) {
    ll s = (x * y > 0 ? 1 : -1);
    return s * (abs(x) / abs(y));
}

ll EVAL(ll x, ll y, char op, bool &fail) {
    // cout << x << " " << op << " " << y << endl;
    if(op == '/' && y == 0) {
        fail = true;
        return 0;
    }
    return (
        op == '+' ? x + y :
        op == '-' ? x - y :
        op == '*' ? x * y :
        op == '/' ? safe_div(x, y) :
        0
    );
}

ll NUM(string &S, vector<int> &ord, int &i) {
    ll ret = 0;
    while(i < S.size() && isdigit(S[i])) {
        ret *= 10;
        ret += S[i] - '0';
        i += 1;
    }
    return ret;
}

ll EXPR(string &S, vector<int> &ord, int &i, bool &fail) {
    vector<int> p;
    vector<ll> vals;
    vector<char> ops;
    while(true) {
        ll val;
        if(isdigit(S[i])) {
            val = NUM(S, ord, i);
        }else {
            i += 1;
            val = EXPR(S, ord, i, fail);
            i += 1;
        }
        vals.push_back(val);
        if(i < S.size() && is_operator(S[i])) {
            p.push_back(ord[i]);
            ops.push_back(S[i]);
            i += 1;
        }else {
            break;
        }
    }
    while(!p.empty()) {
        int k = min_element(p.begin(), p.end()) - p.begin();
        ll x = EVAL(vals[k], vals[k + 1], ops[k], fail);
        vals.erase(vals.begin() + k);
        vals.erase(vals.begin() + k);
        ops.erase(ops.begin() + k);
        p.erase(p.begin() + k);
        vals.insert(vals.begin() + k, x);
    }
    return vals[0];
}

bool solve() {
    string S;
    cin >> S;
    if(S == "#") return false;
    int N = S.size();
    vector<int> ops;
    for(int i = 0; i < N; i++) {
        if(is_operator(S[i])) {
            ops.push_back(i);
        }
    }
    int K = ops.size();
    vector<int> P(K), ord(N);
    unordered_set<ll> st;
    iota(P.begin(), P.end(), 0);
    do {
        for(int i = 0; i < K; i++) {
            ord[ops[i]] = P[i];
        }
        int i = 0;
        bool fail = false;
        ll x = EXPR(S, ord, i, fail);
        if(!fail) st.insert(x);
    }while(next_permutation(P.begin(), P.end()));
    cout << st.size() << endl;
    return true;
}

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

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

using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vd = vector<double>;
using vvd = vector<vd>;
using vvvd = vector<vvd>;
#define all(A) A.begin(),A.end()
#define ALL(A) A.begin(),A.end()
#define rep(i, n) for (int i = 0; i < (int) (n); i++)
template<class T>
void chmax(T& p, T q) { if (p < q)p = q; };

void solve(string S) {
    ll N=S.size();
    vector<vector<set<ll>>> DP(N,vector<set<ll>>(N));
    for(ll d=0;d<N;d++){
        rep(i,N){
            ll j=i+d;
            if(j>=N)continue;
            //[i,j]

            bool is_num=1;
            ll f=0;
            for(ll k=i;k<=j;k++){
                if('0'<=S[k]&&S[k]<='9'){
                    f=10*f+S[k]-'0';
                }
                else is_num=0;
            }
            if(is_num){
                DP[i][j].insert(f);
                continue;
            }
            else if(d>1&&S[i]=='('&&S[j]==')'){
                DP[i][j]=DP[i+1][j-1];
            }

            for(ll k=i+1;k<j;k++){
                if(S[k]=='+'){
                    for(auto d:DP[i][k-1]){
                        for(auto e:DP[k+1][j]){
                            DP[i][j].insert(d+e);
                        }
                    }
                }
                if(S[k]=='*'){
                    for(auto d:DP[i][k-1]){
                        for(auto e:DP[k+1][j]){
                            DP[i][j].insert(d*e);
                        }
                    }
                }
                if(S[k]=='-'){
                    for(auto d:DP[i][k-1]){
                        for(auto e:DP[k+1][j]){
                            DP[i][j].insert(d-e);
                        }
                    }
                }
                if(S[k]=='/'){
                    for(auto d:DP[i][k-1]){
                        for(auto e:DP[k+1][j]){
                            if(e!=0)DP[i][j].insert(d/e);
                        }
                    }
                }
            }
        }
    }
    cout<<DP[0][N-1].size()<<endl;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);


    string S;
    while (cin >> S) {
        if (S == "#")return 0;
        solve(S);
    }

}
accuracy: 1
time_ms: 10
memory_kb: 4056
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define ALL(v) v.begin(),v.end()
#define dbg(x) cerr << #x << ": " << (x) << endl;
template<class F, class S>
ostream& operator<<(ostream& os, pair<F,S>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template<class Iter>
void print(Iter beg, Iter end) {
    for (Iter itr = beg; itr != end; ++itr) {
        cerr << *itr << ' ';
    }
    cerr << '\n';
}
#define BAD (1e9 + 1)

class UnionFind {
public:
	UnionFind(int n, const vector<vector<int>>& init)
	: n(n), par(n), rank(n, 1), ev(init) {
		iota(par.begin(), par.end(), 0);
	}
	int root(int x) {
		if (par[x] == x) return x;
		return par[x] = root(par[x]);
	}
	bool unite(int x, int y, char op) {
		x = root(x);
		y = root(y);
		if (x== y) return false;

        vector<int> e;
        for (int a : ev[x]) {
            for (int b : ev[y]) {
                if (op == '+') e.push_back(a + b);
                else if (op == '-') e.push_back(a - b);
                else if (op == '*') e.push_back(a * b);
                else if (op == '/') {
                    if (b != 0) e.push_back(a / b);
                }
            }
        }
        sort(ALL(e));
        e.erase(unique(ALL(e)), e.end());
		if (rank[x] > rank[y]) swap(x,y);
		par[x] = y;
		if (rank[x] == rank[y]) ++rank[y];
        ev[y] = e;

        return true;
	}
	bool same(int x, int y) {
		return root(x) == root(y);
	}
    vector<int> eval(int x) {
        return ev[root(x)];
    }
private:
	int n;
	vector<int> par, rank;
    vector<vector<int>> ev;
};
string s;
using State = string::iterator;
/*
expr = term op term
term = ( expr ) | number
*/
vector<int> expr(State& itr);
vector<int> term(State& itr);
int number(State& itr);

vector<int> expr(State& itr) {
    vector<vector<int>> a;
    vector<char> op;
    a.push_back(term(itr));
    while (*itr == '+' || *itr == '-' || *itr == '*' || *itr == '/') {
        op.push_back(*itr);
        ++itr;
        a.push_back(term(itr));
    }
    vector<int> order(op.size());
    vector<int> res;
    iota(ALL(order), 0);
    do {
        UnionFind uf(a.size(), a);
        for (int o : order) {
            uf.unite(o, o+1, op[o]);
        }
        auto r = uf.eval(0);
        res.insert(res.end(), ALL(r));
    } while (next_permutation(ALL(order)));
    sort(ALL(res));
    res.erase(unique(ALL(res)), res.end());
    return res;
}
vector<int> term(State& itr) {
    if (*itr == '(') {
        ++itr;
        auto res = expr(itr);
        ++itr;
        return res;
    } else if (isdigit(*itr)) {
        return { number(itr) };
    } else {
        assert(false);
    }
}
int number(State& itr) {
    int res = 0;
    while (isdigit(*itr)) {
        res *= 10;
        res += *itr - '0';
        ++itr;
    }
    return res;
}

ll solve() {
    getline(cin,s);
    if (s == "#") exit(0);
    auto itr = s.begin();
    return expr(itr).size();
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    while (true) {
        cout << solve() << '\n';
    }
}
accuracy: 1
time_ms: 2230
memory_kb: 6480
final_rank: 18

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

using namespace std;

template<class t>
void output(set<t> vs);

void output(int v);
void output(char v);

template<class t>
void output(vector<t> vs){
    cout << "[";
    for(auto i:vs){
        output(i);
        cout << ",";
    }
    cout << "]";
}

void output(int v){
    cout << v;
}

void output(char v){
    cout << v;
}

template<class t>
void output(set<t> vs){
    cout << "{";
    for(auto i:vs){
        output(i);
        cout << ",";
    }
    cout << "}";
}

set<int> decalt(set<int> a,set<int> b,function<pair<bool,int>(int,int)> f){
    set<int> res;
    for(auto i:a){
        for(auto j:b){
            pair<bool,int> t = f(i,j);
            if(not t.first)continue;
            res.insert(t.second);
        }
    }
    return res;
}

struct parser {
    string str;
    int p;
    parser(string str):str(str),p(0){}

    bool end(){
        return p >= (int)str.size();
    }

    bool read_char(char c){
        if(end())return false;
        if(str[p]!=c)return false;
        ++p;
        return true;
    }

    bool read_op(char &res){
        string ops = "+-*/";
        for(auto op:ops){
            if(read_char(op)){
                res = op;
                return true;
            }
        }
        return false;
    }

    bool read_digit(int &res){
        for(char i='0';i<='9';++i){
            if(read_char(i)){
                res = i - '0';
                return true;
            }
        }
        return false;
    }

    bool read_number(int &res){
        if(not read_digit(res)){
            return false;
        }
        while(true){
            int add;
            if(not read_digit(add))break;
            res = res * 10 + add;
        }
        return true;
    }

    bool read_factor(set<int> &res){
        do{
            if(not read_char('('))break;
            assert(read_expr(res));
            assert(read_char(')'));
            return true;
        }while(false);

        do{
            int num;
            if(not read_number(num))break;
            res.clear();
            res.insert(num);
            return true;
        }while(false);
        assert(false);
    }

    bool read_expr(set<int> &res){
        set<int> head;
        assert(read_factor(head));
        vector<set<int>> nums;
        vector<char> ops;
        nums.push_back(head);
        while(true){
            char op;
            set<int> rest;
            if(not read_op(op))break;
            assert(read_factor(rest));
            ops.push_back(op);
            nums.push_back(rest);
        }
        res = solve(nums, ops);
        return true;
    }

    set<int> solve(vector<set<int>> nums,vector<char> op){
        assert(nums.size()==op.size()+1);
        if(nums.size()==1){
            return nums[0];
        }
        map<char,function<pair<bool,int>(int,int)>> opfs;
        opfs['+'] = [](int a,int b){
            return make_pair(true,a+b);
        };
        opfs['-'] = [](int a,int b){
            return make_pair(true,a-b);
        };
        opfs['*'] = [](int a,int b){
            return make_pair(true,a*b);
        };
        opfs['/'] = [](int a,int b){
            if(b==0)return make_pair(false,0);
            return make_pair(true,a/b);
        };
        set<int> res;
        for(int i=0;i<(int)op.size();++i){
            set<int> t = decalt(nums[i], nums[i+1], opfs[op[i]]);
            vector<set<int>> nnums;
            nnums.insert(nnums.end(),nums.begin(),nums.begin()+i);
            nnums.push_back(t);
            nnums.insert(nnums.end(),nums.begin()+i+2,nums.end());

            vector<char> nop;
            nop.insert(nop.end(),op.begin(),op.begin()+i);
            nop.insert(nop.end(),op.begin()+i+1,op.end());
            assert(nums.size() > nnums.size());
            assert(op.size() > nop.size());
            for(auto i:solve(nnums,nop)){
                res.insert(i);
            }
        }
        return res;
    }

};

int main(){
    string str;
    while(cin >> str and str != "#"){
        parser p(str);
        set<int> ans;
        assert(p.read_expr(ans));
        cout << ans.size() << endl;
    }
}
accuracy: 1
time_ms: 2970
memory_kb: 3560
final_rank: 13

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

vector<int> operator+(const vector<int>& lhs, const vector<int>& rhs) {
    vector<int> res;
    for (auto l : lhs) for (auto r : rhs) {
        res.push_back(l + r);
    }
    sort(res.begin(), res.end());
    res.erase(unique(res.begin(), res.end()), res.end());
    return res;
}

vector<int> operator-(const vector<int>& lhs, const vector<int>& rhs) {
    vector<int> res;
    for (auto l : lhs) for (auto r : rhs) {
        res.push_back(l - r);
    }
    sort(res.begin(), res.end());
    res.erase(unique(res.begin(), res.end()), res.end());
    return res;
}

vector<int> operator*(const vector<int>& lhs, const vector<int>& rhs) {
    vector<int> res;
    for (auto l : lhs) for (auto r : rhs) {
        res.push_back(l * r);
    }
    sort(res.begin(), res.end());
    res.erase(unique(res.begin(), res.end()), res.end());
    return res;
}

vector<int> operator/(const vector<int>& lhs, const vector<int>& rhs) {
    vector<int> res;
    for (auto l : lhs) for (auto r : rhs) {
        if (r == 0) continue;
        res.push_back(l / r);
    }
    sort(res.begin(), res.end());
    res.erase(unique(res.begin(), res.end()), res.end());
    return res;
}

struct node {
    vector<node*> child;
    vector<char> ops;
    vector<int> vals;
    int num = -1;
};

bool isNum(char c) {
    return '0' <= c and c <= '9';
}

bool isOp(char c) {
    return c == '+' or c == '-' or c == '*' or c == '/';
}

struct parser {
    string S;
    int it = 0;
    parser(string S) : S(S), it(0) {}

    node* num() {
        // cout << it << ' ' << "num" << " called" << endl;
        node* res = new node();
        if (S[it] == '(') {
            it++;
            res = expr();
            assert(S[it] == ')');
            it++;
            return res;
        }
        else {
            int v = 0;
            while (isNum(S[it])) {
                v = (v * 10) + (S[it] - '0');
                it++;
            }
            res->vals.push_back(v);
            res->num = v;
            return res;
        }
    }

    node* expr() {
        // cout << it << ' ' << "expr" << " called" << endl;
        node* res = new node();
        do {
            res->child.push_back(num());
            if (it == (int)S.size()) break;
            if (S[it] == ')') break;
            assert(isOp(S[it]));
            // cout << S[it] << ' ';
            res->ops.push_back(S[it]);
            it++;
        } while (true);
        return res;
    }
};

void mymerge(vector<int>& lhs, const vector<int>& rhs) {
    for (auto r : rhs) lhs.push_back(r);
    sort(lhs.begin(), lhs.end());
    lhs.erase(unique(lhs.begin(), lhs.end()), lhs.end());
}

inline vector<int> operation(const vector<int>& lhs, char op, const vector<int>& rhs) {
    assert(isOp(op));
    vector<int> res;
    if (op == '+') {
        res = lhs + rhs;
    }
    if (op == '-') {
        res = lhs - rhs;
    }
    if (op == '*') {
        res = lhs * rhs;
    }
    if (op == '/') {
        res = lhs / rhs;
    }
    return res;
}

vector<int> calcThisOrder(vector<vector<int>> values, vector<char> ops, vector<int> idx) {
    // cout << "order is" << ' ';
    // for (auto i : idx) cout << i << ' ';
    // cout << endl;
    reverse(idx.begin(), idx.end());
    while (idx.size()) {
        int now = idx.back();

        assert(now + 1 < (int)values.size()); 
        
        // cout << "operation" << endl;
        // cout << "   ";
        // for (auto x : values[now]) cout << x << ' ';
        // cout << endl;
        // cout << ops[now] << endl;
        // cout << "   ";
        // for (auto x : values[now + 1]) cout << x << ' ';
        // cout << endl;
        // cout << "---------------" << endl;
        vector<int> cond = operation(values[now], ops[now], values[now + 1]);
        // cout << "cond is" << endl;
        // for (auto x : cond) cout << x << ' ';
        // cout << endl;
        ops.erase(ops.begin() + now);
        values.erase(values.begin() + now);
        values.erase(values.begin() + now);

        values.insert(values.begin() + now, cond);

        // cout << "end insert" << endl;
        // for (auto arr : values) {
        //     cout << "   ";
        //     for (auto x : arr) cout << x << ' ';
        //     cout << endl;
        // }
        // cout << "---------------" << endl;

        idx.pop_back();
        for (auto& i : idx) if (i > now) i--;

        // cout << "next index" << endl;
        // cout << "  ";
        // for (auto i : idx) cout << i << ' ';
        // cout << endl;
    }
    // cout << endl;
    assert(values.size() == (size_t)1);
    return values[0];
}

vector<int> bruteForce(const vector<vector<int>>& values, const vector<char>& ops) {
    assert(ops.size() + 1 == values.size());
    vector<int> res;
    vector<int> idx(ops.size());
    iota(idx.begin(), idx.end(), 0);

    do {
        vector<int> rhs = calcThisOrder(values, ops, idx);
        mymerge(res, rhs);

    } while (next_permutation(idx.begin(), idx.end()));

    return res;
}

vector<int> dfs(node* v) {
    if (v->vals.size()) {
        return v->vals;
    }
        
    assert(v->ops.size() + 1 == v->child.size());

    vector<vector<int>> values;
    for (const auto& x : v->child) values.push_back(dfs(x));

    // cout << "calc start" << endl;
    // for (auto val : values) {
    //     cout << "   ";
    //     for (auto x : val) cout << x << ' ';
    //     cout << endl;
    // }
    // cout << "-------------" << endl;
    
    vector<int> res = bruteForce(values, v->ops);

    return v->vals = res;
}

bool solve() {
    cin.tie(nullptr)->sync_with_stdio(false);
    string S; cin >> S;
    if (S == "#") return false;

    parser P(S);
    auto root = P.expr();

    auto ans = dfs(root);
    cout << ans.size() << endl;

    return true;
}

int main() {
    while (solve()) ;
}
accuracy: 1
time_ms: 5730
memory_kb: 3592
final_rank: 15

code_snippet: # include <bits/stdc++.h>
# define len(v) (ll(std::size(v)))
# define all(v) std::begin(v), std::end(v)
# define rep(i, a, b) for (ll i = a; i < ll(b); i++)
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
string erase_all_space(string s) { s.erase(remove_if(all(s), [](char c){ return isspace(c); }), s.end()); return s; }

constexpr ll MOD = ll(1e9) + 7;

struct Parser {
   string s;
   string::const_iterator it;
   vector<ll> ops;
   vector<int> ord;
   bool zflag;
   Parser() = default;
   Parser(const string& _s, const vector<ll> _ops) : s(_s), ops(_ops), ord(_s.size(), -1), zflag(false) {
      it = s.begin();
      int cur = 0;
      rep (i, 0, len(s)) {
         if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
            ord[i] = ops[cur];
            cur++;
         }
      }
   }

   ll parse() {
      return expr();
   }

   ll expr(int depth = 0) {
      if (depth == len(ops)) {
         if (*it == '(') {
            assert(*it++ == '(');
            ll val = expr();
            assert(*it++ == ')');
            return val;
         }
         else {
            return number();
         }
      }

      ll acc = expr(depth + 1);
      while (it != s.end() && *it != ')' && ord[distance(s.cbegin(), it)] == depth) {
         char op = *it++;
         ll other = expr(depth + 1);
         acc = eval(acc, op, other);
      }

      return acc;
   }

   ll number() {
      ll ret = 0;
      for (; isdigit(*it); ++it) {
         ret = 10LL * ret + (*it - '0');
      }
      return ret;
   }

   ll eval(ll a, char op, ll b) {
      switch (op) {
         case '+': return a + b;
         case '-': return a - b;
         case '*': return a * b;
         case '/': if (b == 0) { zflag = true; b = 1; } return a / b;
      }
      assert(false);
   }
};

int main() {
   while (true) {
      string s;
      getline(cin, s);
      if (s == "#") break;
      int sum = count(all(s), '+') + count(all(s), '-') + count(all(s), '*') + count(all(s), '/');
      set<ll> st;

      vector<ll> ops(sum, 0);
      iota(all(ops), 0);
      do {
         Parser parser(s, ops);
         ll res = parser.parse();
         if (not parser.zflag) st.insert(res);
      } while (next_permutation(all(ops)));

      cout << st.size() << endl;
   }
}
accuracy: 1
time_ms: 1590
memory_kb: 3400
final_rank: 7

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

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)
#define all(v) v.begin(), v.end()

using ll = long long;
using ld = long double;
using ull = unsigned long long;

template <typename T> bool chmin(T &a, const T &b) {
    if (a <= b) return false;
    a = b;
    return true;
}
template <typename T> bool chmax(T &a, const T &b) {
    if (a >= b) return false;
    a = b;
    return true;
}

#define debug(...)                                                     \
    std::cerr << "LINE: " << __LINE__ << " [" << #__VA_ARGS__ << "]:", \
        debug_out(__VA_ARGS__)

void debug_out() {
    std::cerr << std::endl;
}

template <typename Head, typename... Tail> void debug_out(Head h, Tail... t) {
    std::cerr << " " << h;
    if (sizeof...(t) > 0) std::cerr << " :";
    debug_out(t...);
}

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa) {
    return os << pa.first << " " << pa.second;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
    for (std::size_t i = 0; i < vec.size(); i++)
        os << vec[i] << (i + 1 == vec.size() ? "" : " ");
    return os;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::set<T> &set) {
    for(auto x: set) {
        os << x << " ";
    }
    return os;
}

typedef std::string::const_iterator State;

bool expect(State &begin, char expected) {
    return *begin == expected;
}

void consume(State &begin, char expected) {
    assert(*begin == expected);
    begin++;
}

bool isdigit(char c) {
    return '0' <= c && c <= '9';
}

bool isAlpha(char c) {
    return 'A' <= c && c <= 'Z';
}

bool isalpha(char c) {
    return 'a' <= c && c <= 'z';
}

std::set<ll> stmt(State &);
std::set<ll> expr(State &);

int is_op(State &begin) {
    if (expect(begin, '+'))
        return 0;
    else if (expect(begin, '-'))
        return 1;
    else if (expect(begin, '*'))
        return 2;
    else if (expect(begin, '/'))
        return 3;
    else
        return -1;
}

struct Op {
    int type = -1;
    std::set<ll> lhs, rhs;
};

std::set<ll> stmt(State &begin) {
    auto now = expr(begin);
    std::vector<Op> a;
    while (is_op(begin) >= 0) {
        int type = is_op(begin);
        consume(begin, *begin);
        auto rhs = expr(begin);
        Op p;
        p.type = type;
        p.lhs = now;
        p.rhs = rhs;
        now = rhs;
        a.emplace_back(p);
    }
    if(a.empty()) {
        return now;
    }
    int n = a.size();
    std::vector<int> idxs(n);
    std::iota(all(idxs), 0);
    std::set<ll> res;
    do {
        auto op = a;
        std::vector<int> used(n, -1);
        for (auto i : idxs) {
            used[i] = 1;
            auto &[type, lhs, rhs] = op[i];
            std::set<ll> ret;
            for (auto x : lhs) {
                for (auto y : rhs) {
                    if (type == 0) {
                        ret.insert(x + y);
                    } else if (type == 1) {
                        ret.insert(x - y);
                    } else if (type == 2) {
                        ret.insert(x * y);
                    } else if (type == 3) {
                        if (y != 0) ret.insert(x / y);
                    } else
                        assert(0);
                }
            }
            if (idxs.back() == i) {
                res.merge(ret);
                break;
            }
            rrep(j,0,i) {
                if(used[j] < 0) {
                    op[j].rhs = ret;
                    break;
                }
            }
            rep(j,i+1,n) {
                if(used[j] < 0) {
                    op[j].lhs = ret;
                    break;
                }
            }
        }
    } while (std::next_permutation(all(idxs)));
    return res;
}

std::set<ll> expr(State &begin) {
    if (expect(begin, '(')) {
        consume(begin, '(');
        auto res = stmt(begin);
        consume(begin, ')');
        return res;
    } else if (isdigit(*begin)) {
        ll num = 0;
        while (isdigit(*begin)) {
            num *= 10;
            num += *begin - '0';
            consume(begin, *begin);
        }
        return {num};
    } else
        assert(0);
}

int main() {
    std::string s;
    while (std::cin >> s, !(s == "#")) {
        State begin = s.begin();
        int ans = stmt(begin).size();
        std::cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 3930
memory_kb: 3484
final_rank: 14

code_snippet: #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unordered_set>
#include <algorithm>
using namespace std;

char s[256];

unordered_set<int> parse(int stt, int edd) {
    unordered_set<int> res;
    unordered_set<int> oper[12][12];
    int num[12][12], perm[12];
    char oc[16] = { 0, };
    int level = 0, itv = 0, pcnt = 0, tx, np, ocp;
    for (int i = stt; i <= edd; i++) {
        if (s[i] == '(') {
            level++;
            if (level == 1) itv = i;
        }
        else if (s[i] == ')') {
            level--;
            if (level == 0) oper[0][pcnt++] = parse(itv + 1, i - 1);
        }
        else if (level > 0) continue;
        else if (isdigit(s[i]) && (i == 0 || !isdigit(s[i - 1]))) {
            oper[0][pcnt++] = { (int)strtoll(&s[i], NULL, 10) };
        }
        else oc[pcnt - 1] = s[i];
    }

    for (int i = 0; i < pcnt - 1; i++) {
        perm[i] = i;
        num[0][i] = i;
    }
    do {
        for (int i = 1; i < pcnt; i++) {
            np = num[i - 1][perm[i - 1]];
            ocp = perm[i - 1];
            for (int j = 0; j < np; j++) oper[i][j] = oper[i - 1][j];
            oper[i][np] = {};
            for (int j : oper[i - 1][np]) {
                for (int k : oper[i - 1][np + 1]) {
                    if (oc[ocp] == '/' && k == 0) continue;
                    if (oc[ocp] == '+') tx = j + k;
                    else if (oc[ocp] == '-') tx = j - k;
                    else if (oc[ocp] == '*') tx = j * k;
                    else if (oc[ocp] == '/') tx = j / k;
                    oper[i][np].insert(tx);
                }
            }
            for (int j = np + 1; j < pcnt - i; j++) oper[i][j] = oper[i - 1][j + 1];
            for (int j = 0; j < pcnt - 1; j++) {
                if (j == perm[i - 1]) num[i][j] = -1;
                else if (j > perm[i - 1]) num[i][j] = num[i - 1][j] - 1;
                else num[i][j] = num[i - 1][j];
            }
        }
        for (int i : oper[pcnt - 1][0]) res.insert(i);
    } while (next_permutation(&perm[0], &perm[pcnt - 1]));

    return res;
}

int main(void) {
    while (1) {
        scanf("%s", s);
        if (s[0] == '#') break;
        printf("%d\n", (signed int)(parse(0, strlen(s) - 1).size()));
    }
    return 0;
}
accuracy: 1
time_ms: 3870
memory_kb: 3068
final_rank: 12

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
using namespace __gnu_pbds;
using namespace std;

#pragma GCC optimize("O3")
// #pragma GCC target("avx2")
// #pragma GCC optimize("unroll-loops")
#define all(x) (x).begin(), (x).end()
#define reall(a) (a).rbegin(), (a).rend()
#define Sort(x) sort((x).begin(), (x).end())
#define Reverse(x) reverse((x).begin(), (x).end())
#define len(x) (ll) x.size()
#define pb emplace_back
#define append emplace_back
#define STR(x) to_string(x)
#define INT(x) stoi(x)
#define ll(x) stoll(x)
#define DOUBLE(x) stod(x)
#define ld(x) stold(x)

#define elif else if
#define sum(...) accumulate(all(__VA_ARGS__), 0LL)
#define bisect_left(arr, k) lower_bound(all(arr), (k)) - (arr).begin()
// #define bisect_right(arr, k) upper_bound(all(arr), (k)) - (arr).begin()
#define uniq(arr)                                                                                                      \
    sort(all(arr));                                                                                                    \
    arr.erase(unique(all(arr)), end(arr))

using str = string;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using ui = unsigned int;
using puu = pair<ui, ui>;
// using P = pair<int, int>;
using vi = vector<int>;
using vll = vector<long long>;
// template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,
// tree_order_statistics_node_update>;
template <typename S, typename T>
using ordered_dict = tree<S, T, less<S>, rb_tree_tag, tree_order_statistics_node_update>;
/*
var_name.find_by_order(k) でk番目（0-indexed）のiteratorを返す．
var_name.order_of_key(key) でkey以上の最初の要素が、treeの中で何番目か返す．
*/
// rep-------------------------------------------------------------------
#define overload4(_1, _2, _3, _4, name, ...) name
#define overload3(_1, _2, _3, name, ...) name
#define rep1(n) for (ll tukacchadame = 0; tukacchadame < n; ++tukacchadame)
#define rep2(i, n) for (ll i = 0; i < n; ++i)
#define rep3(i, a, b) for (ll i = a; i < b; ++i)
#define rep4(i, a, b, c) for (ll i = a, _bb = b; (c > 0 && i < _bb) || (c < 0 && i > _bb); i += c)
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define each1(i, a) for (auto &&i : a)
#define each2(x, y, a) for (auto &&[x, y] : a)
#define each3(x, y, z, a) for (auto &&[x, y, z] : a)
#define each(...) overload4(__VA_ARGS__, each3, each2, each1)(__VA_ARGS__)
// ----------------------------------------------------------------------

// 入出力-----------------------------------------------------------------
struct Ioinitializer {
    Ioinitializer() noexcept {
        cin.tie(nullptr);
        ios::sync_with_stdio(false);
        cout << setprecision(20) << setiosflags(ios::fixed);
    }
} Ioinitializer;

struct input {
    input(){};
    operator int() {
        int value;
        cin >> value;
        return value;
    }
    operator long long() {
        long long value;
        cin >> value;
        return value;
    }
    operator unsigned long long() {
        unsigned long long value;
        cin >> value;
        return value;
    }
    operator unsigned() {
        unsigned value;
        cin >> value;
        return value;
    }
    operator float() {
        float value;
        cin >> value;
        return value;
    }
    operator double() {
        double value;
        cin >> value;
        return value;
    }
    operator long double() {
        long double value;
        cin >> value;
        return value;
    }
    operator char() {
        char value;
        do {
            value = getchar();
        } while (value == ' ' || value == '\n');
        return value;
    }
    operator string() {
        string value;
        cin >> value;
        return value;
    }
};
void scan(int &a) {
    cin >> a;
}
void scan(unsigned &a) {
    cin >> a;
}
void scan(long &a) {
    cin >> a;
}
void scan(long long &a) {
    cin >> a;
}
void scan(unsigned long long &a) {
    cin >> a;
}
void scan(char &a) {
    do {
        a = getchar();
    } while (a == ' ' || a == '\n');
}
void scan(float &a) {
    cin >> a;
}
void scan(double &a) {
    cin >> a;
}
void scan(long double &a) {
    cin >> a;
}
void scan(vector<bool> &a) {
    for (unsigned i = 0; i < a.size(); i++) {
        int b;
        scan(b);
        a[i] = b;
    }
}
void scan(char a[]) {
    cin >> a;
}
void scan(string &a) {
    cin >> a;
}
template <class T> void scan(vector<T> &);
template <class T, size_t size> void scan(array<T, size> &);
template <class T, class L> void scan(pair<T, L> &);
template <class T, size_t size> void scan(T (&)[size]);
template <class T> void scan(vector<T> &a) {
    for (auto &&i : a)
        scan(i);
}
template <class T> void scan(deque<T> &a) {
    for (auto &&i : a)
        scan(i);
}
template <class T, size_t size> void scan(array<T, size> &a) {
    for (auto &&i : a)
        scan(i);
}
template <class T, class L> void scan(pair<T, L> &p) {
    scan(p.first);
    scan(p.second);
}
template <class T, size_t size> void scan(T (&a)[size]) {
    for (auto &&i : a)
        scan(i);
}
template <class T> void scan(set<T> &a, int n) {
    for (int i = 0; i < n; i++)
        a.insert(input());
}

template <class T> void scan(T &a) {
    cin >> a;
}
template <class A, class B> ostream &operator<<(ostream &ost, const pair<A, B> &p) {
    ost << "{" << p.first << ", " << p.second << "}";
    return ost;
}
template <class T> ostream &operator<<(ostream &ost, const vector<T> &v) {
    ost << "[";
    for (int i = 0; i < (int)v.size(); i++) {
        if (i)
            ost << ", ";
        ost << v[i];
    }
    ost << "]";
    return ost;
}
template <class A, class B> ostream &operator<<(ostream &ost, const map<A, B> &v) {
    bool k = false;
    ost << "{";
    for (auto p : v) {
        if (k) {
            ost << ", ";
        }
        ost << "(" << p.first << ", " << p.second << ")";
        k = true;
    }
    ost << "}";
    return ost;
}
template <class T> ostream &operator<<(ostream &ost, const set<T> &v) {
    bool k = false;
    ost << "{";
    for (auto p : v) {
        if (k) {
            ost << ", ";
            k = true;
        }
        ost << p;
        k = true;
    }
    ost << "}";
    return ost;
}
template <class T> ostream &operator<<(ostream &ost, const multiset<T> &v) {
    bool k = false;
    ost << "[";
    for (auto p : v) {
        if (k) {
            ost << ", ";
            k = true;
        }
        ost << p;
        k = true;
    }
    ost << "]";
    return ost;
}
template <class T> inline void print(const T &a) {
    cout << a << "\n";
}
template <class T, class... Ts> inline void print(const T &a, const Ts &...ts) {
    cout << a << " ";
    print(ts...);
}
template <class T> inline void print_vec(const vector<T> &a, bool debug = false) {
    for (unsigned i = 0; i < a.size(); ++i) {
        if (debug)
            cout << "[";
        if (i) {
            if (debug)
                cout << ", ";
            else
                cout << " ";
        }
        cout << a[i];
    }
    if (debug)
        cout << "]\n";
    else
        cout << "\n";
}
template <class T> inline void print_vec(const vector<vector<T>> &a, bool debug = false) {
    int n = a.size();
    if (n == 0) {
        if (debug)
            print("[[]]");
        else
            print("");
        return;
    }
    for (int i = 0; i < n; ++i) {
        if (debug)
            cout << "[";
        for (unsigned j = 0; j < a[i].size(); ++j) {
            if (j) {
                if (debug)
                    cout << ", ";
                else
                    cout << " ";
            }
            cout << a[i][j];
        }
        if (debug)
            cout << "]\n";
        else
            cout << "\n";
    }
}
// -----------------------------------------------------------------------
// 関数群
template <class T> vector<T> vec(size_t a) {
    return vector<T>(a);
}
template <class T, class... Ts> auto vec(size_t a, Ts... ts) {
    return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...));
}
template <typename T> T floor(T a, T b) {
    if (b < 0) {
        a = -a;
        b = -b;
    }
    return a >= 0 ? a / b : (a - b + 1) / b;
}
template <typename T> T ceil(T a, T b) {
    if (b < 0) {
        a = -a;
        b = -b;
    }
    return a >= 0 ? (a + b - 1) / b : a / b;
}

template <class T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T> auto min(const T &a) {
    return *min_element(a.begin(), a.end());
}
template <class T> auto max(const T &a) {
    return *max_element(a.begin(), a.end());
}
template <class ll> long long intpow(ll a, ll b) {
    long long ans = 1;
    while (b) {
        if (b & 1)
            ans *= a;
        a *= a;
        b >>= 1;
    }
    return ans;
}
long long modpow(ll a, ll b, ll p) {
    long long ans = p == 1 ? 0 : 1;
    long long s = a % p;
    while (b) {
        if (b & 1)
            (ans *= s) %= p;
        (s *= s) %= p;
        b >>= 1;
    }
    return ans;
}
template <typename A> A lcm(const vector<A> &a) {
    A res;
    res = a[0];
    for (int i = 1; i < a.size(); i++) {
        res = lcm(res, a[i]);
    }
    return res;
}
template <typename A> A gcd(const vector<A> &a) {
    A res;
    res = a[0];
    for (int i = 1; i < a.size() && res != 1; i++) {
        res = gcd(a[i], res);
    }
    return res;
}
int popcount(int n) {
    return __builtin_popcount(n);
}
int popcount(ll n) {
    return __builtin_popcountll(n);
}
template <typename T> int bit_length(T n) {
    int k = 0;
    while (n) {
        k++;
        n /= 2;
    }
    return k;
}
template <typename A> A isqrt(A n) {
    A a = 0, r = 0;
    for (A s = bit_length(n) - (bit_length(n) % 2 ? 1 : 2); s >= 0; s -= 2) {
        A t = ((n >> s) & 3);
        r = ((r << 2) | t);
        A c = ((a << 2) | 1);
        int b = (r >= c);
        if (b) {
            r -= c;
        }
        a = ((a << 1) | b);
    }
    return a;
}
template <typename T> T add(T a, T b) {
    T res;
    if (a < 0 && b < 0)
        return __builtin_add_overflow(a, b, &res) ? numeric_limits<T>::min() : res;
    return __builtin_add_overflow(a, b, &res) ? numeric_limits<T>::max() : res;
}
template <typename T> T mul(T a, T b) {
    T res;
    if ((a < 0 and b > 0) or (a > 0 and b < 0))
        return __builtin_mul_overflow(a, b, &res) ? numeric_limits<T>::min() : res;
    return __builtin_mul_overflow(a, b, &res) ? numeric_limits<T>::max() : res;
}

template <typename T> int count(const vector<T> &a, const T k) {
    int res = 0;
    for (T val : a)
        if (val == k)
            res++;
    return res;
}

int count(const string &s, const char &k) {
    int res = 0;
    for (char val : s)
        if (val == k)
            res++;
    return res;
}

int count(const string &s, const string &k) {
    int res = 0, n = len(k);
    for (int i = 0; i < len(s) - n + 1; i++)
        if (k == s.substr(i, n)) {
            res++;
            i += n - 1;
        }
    return res;
}

template <typename T> map<T, int> Counter(const vector<T> &a) {
    map<T, int> mp;
    for (T val : a)
        mp[val]++;
    return mp;
}
template <typename S, typename T> vector<T> values(const map<S, T> &mp) {
    int n = mp.size(), i = 0;
    vector<T> res(n);
    for (auto [itm, val] : mp)
        res[i++] = val;
    return res;
}
template <typename S, typename T> vector<S> keys(const map<S, T> &mp) {
    int n = mp.size(), i = 0;
    vector<S> res(n);
    for (auto [itm, val] : mp)
        res[i++] = itm;
    return res;
}
template <typename T> inline bool contain(const vector<T> &a, const T k) {
    return binary_search(a.begin(), a.end(), k);
}

struct dsu {
  public:
    dsu() : _n(0) {
    }
    explicit dsu(int n) : _n(n), parent_or_size(n, -1) {
    }

    int merge(int a, int b) {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
            std::swap(x, y);
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(int a, int b) {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(int a) {
        assert(0 <= a && a < _n);
        if (parent_or_size[a] < 0)
            return a;
        return parent_or_size[a] = leader(parent_or_size[a]);
    }

    int size(int a) {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    std::vector<std::vector<int>> groups() {
        std::vector<int> leader_buf(_n), group_size(_n);
        for (int i = 0; i < _n; i++) {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        std::vector<std::vector<int>> result(_n);
        for (int i = 0; i < _n; i++) {
            result[i].reserve(group_size[i]);
        }
        for (int i = 0; i < _n; i++) {
            result[leader_buf[i]].push_back(i);
        }
        result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<int> &v) { return v.empty(); }),
                     result.end());
        return result;
    }

  private:
    int _n;
    // root node: -1 * component size
    // otherwise: parent
    std::vector<int> parent_or_size;
};

vector<vector<int>> multiple_loops(const vector<int> &loops) {
    //各 k 対して,loops[k] 回ループする.itertools.productに似ている.

    int loop_count = 1;
    for (int i : loops)
        loop_count *= i;

    if (loop_count == 0)
        return {};

    int n = (int)loops.size();
    vector<int> d(n);
    vector<vector<int>> res = {d};
    for (int _ = 0; _ < loop_count - 1; ++_) {
        d[0]++;
        int i = 0;
        while (i < n and d[i] == loops[i]) {
            d[i] = 0;
            i++;
            d[i]++;
        }
        res.emplace_back(d);
    }
    return res;
}

const int INF = INT_MAX >> 1;
// const ll mod = 1000000007;
// const double PI = acos(-1.0);

struct solve {
    int now = 0;
    string expr;
    int n;

    solve(string s) : expr(s), n(s.size()) {
        print(eval().size());
    }

    vector<int> eval() {
        vector<vector<int>> can;
        vector<char> op;
        while (now < n and expr[now] != ')') {
            if (expr[now] == '(') {
                now++;
                can.emplace_back(eval());
            } else if ('0' <= expr[now] and expr[now] <= '9') {
                can.push_back({read_int()});
            } else {
                op.emplace_back(expr[now]);
                now++;
            }
        }
        now++;
        vector<int> loop_num, v;
        int m = len(op);
        for (auto k : can)
            loop_num.emplace_back(k.size());

        rep(i, m) v.emplace_back(i);
        vector<int> res;
        do {
            for (auto &w : multiple_loops(loop_num)) {
                dsu uf(m + 1);
                vector<int> arr(m + 1);
                bool zero_flag = 0;
                rep(i, m + 1) {
                    arr[i] = can[i][w[i]];
                }
                for (auto k : v) {
                    int s = uf.leader(k), t = uf.leader(k + 1);
                    uf.merge(k, k + 1);
                    int u = uf.leader(k);
                    if (op[k] == '+') {
                        arr[u] = arr[s] + arr[t];
                    } else if (op[k] == '-') {
                        arr[u] = arr[s] - arr[t];
                    } else if (op[k] == '*') {
                        arr[u] = arr[s] * arr[t];
                    } else {
                        if (arr[t] == 0) {
                            zero_flag = 1;
                            break;
                        } else {
                            arr[u] = arr[s] / arr[t];
                        }
                    }
                }
                if (not zero_flag) {
                    res.emplace_back(arr[uf.leader(0)]);
                }
            }
        } while (next_permutation(v.begin(), v.end()));
        uniq(res);
        return res;
    }

    int read_int() {
        int res = 0;
        while (now < n and '0' <= expr[now] and expr[now] <= '9') {
            res = res * 10 + (expr[now] - '0');
            now++;
        }
        return res;
    }
};

int main() {
    while (true) {
        string s = input();
        if (s == "#")
            break;
        solve sol(s);
    }
}
accuracy: 1
time_ms: 670
memory_kb: 6436
final_rank: 16

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

using State = string::const_iterator;

bool valid = true;

int factor(State &begin);
int expression(State &begin);
int term(State &begin);
int number(State &begin);

int factor(State &begin) {
  if (*begin == '(') {
    begin++;
    int ret = expression(begin);
    begin++;
    return ret;
  } else {
    return number(begin);
  }
}

int expression(State &begin) {
  int ret = term(begin);

  while (true) {
    if (*begin == '+') {
      begin++;
      ret += term(begin);
    } else if (*begin == '-') {
      begin++;
      ret -= term(begin);
    } else {
      break;
    }
  }

  return ret;
}

int term(State &begin) {
  int ret = factor(begin);

  while (true) {
    if (*begin == '*') {
      begin++;
      ret *= factor(begin);
    } else if (*begin == '/') {
      begin++;
      int f = factor(begin);
      if (f == 0) {
        valid = false;
        return 0;
      }
      ret /= f;
    } else {
      break;
    }
  }

  return ret;
}

int number(State &begin) {
  int ret = 0;
  while (isdigit(*begin)) {
    ret *= 10;
    ret += *begin - '0';
    begin++;
  }
  return ret;
}

void solve(string in) {
  string u = '(' + in + ')';

  vector< int > idxs;
  for (int i = 0; i < (int)u.size(); i++) {
    if (u[i] == '+' or u[i] == '-' or u[i] == '*' or u[i] == '/') {
      idxs.emplace_back(i);
    }
  }

  set< int > st;
  // cerr << s << endl;
  do {
    string s = u;
    auto is = idxs;
    for (int qi = 0; qi < (int)is.size(); qi++) {
      int i = is[qi];
      int l = i;
      int cntl = 0;
      while (cntl != 1) {
        l--;
        if (s[l] == '(') cntl++;
        if (s[l] == ')') cntl--;
      }
      // cerr << "l: " << l << endl;

      int r = i;
      int cntr = 0;
      while (cntr != 1) {
        r++;
        if (s[r] == ')') cntr++;
        if (s[r] == '(') cntr--;
      }
      // cerr << "r: " << r << endl;

      s = s.substr(0, l) + '(' + s.substr(l, i - l) + ')' + s[i] + '(' + s.substr(i + 1, r - i) + ')' + s.substr(r + 1, s.size());
      // cerr << s.substr(0, l) << ", " << s.substr(l, i - l) << ", " << s[i] << ", " << s.substr(i + 1, r - i) << endl;
      // cerr << s << endl;
      // for  (auto &j: is) cerr << j << " ";
      // cerr << endl;
      for (int j = 0; j < (int)is.size(); j++) {
        if (l <= is[j]) is[j]++;
        if (i <= is[j]) is[j]++;
        if (i + 3 <= is[j]) is[j]++;
        if (r + 3 <= is[j]) is[j]++;
      }

      // for  (auto &j: is) cerr << j << " ";
      // cerr << endl;

      // for (auto &j: is) cerr << s[j] << endl;
      // break;
    }

    State begin = s.begin();
    valid = true;

    int res = factor(begin);
    if (valid) st.insert(res);
    // break;
  } while (next_permutation(idxs.begin(), idxs.end()));

  cout << st.size() << endl;
}

int main() {
  string s;

  while (cin >> s, s.front() != '#') {
    solve(s);
  }
}
accuracy: 1
time_ms: 7770
memory_kb: 3320
final_rank: 17

code_snippet: #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define _GLIBCXX_DEBUG
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using ll=long long;
using ld=long double;
ll ILL=1167167167167167167;
const int INF=2100000000;
const ll mod=998244353;
#define rep(i,a) for (ll i=0;i<a;i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> ll LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> ll UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
void yneos(bool a){if(a) cout<<"Yes\n"; else cout<<"No\n";}
template<class T> void vec_out(vector<T> &p){for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}

set<int> g(vector<set<int>> &p,vector<char> &q){
	int l=q.size();
	if(l==0) return p[0];
	set<int> s;
	rep(i,l){
		auto n_p=p;
		auto n_q=q;
		set<int> n_s;
		for(auto x:n_p[i]) for(auto y:n_p[i+1]){
			int tmp;
			if(q[i]=='+'){
				tmp=x+y;
			}else if(q[i]=='-'){
				tmp=x-y;
			}else if(q[i]=='*'){
				tmp=x*y;
			}else{
				if(y==0) tmp=INF;
				else tmp=x/y;
			}
			if(tmp!=INF) n_s.insert(tmp);
		}
		for(int j=i+1;j<l;j++){
			swap(n_q[j-1],n_q[j]);
			swap(n_p[j],n_p[j+1]);
		}
		n_q.resize(l-1);
		n_p.resize(l);
		n_p[i]=n_s;
		auto tmp=g(n_p,n_q);
		for(auto x:tmp) s.insert(x);
	}
	return s;
}

set<int> f(string S,int &ind){
	vector<set<int>> p;
	vector<char> q;
	while(true){
		if(ind==(int)(S.size())||S[ind]==')'){
			ind++;
			return g(p,q);
		}
		else if(S[ind]=='('){
			ind++;
			p.push_back(f(S,ind));
		}else if('0'<=S[ind]&&S[ind]<='9'){
			int tmp=0;
			while(ind!=(int)(S.size())&&'0'<=S[ind]&&S[ind]<='9'){
				tmp*=10;
				tmp+=(int)(S[ind]-'0');
				ind++;
			}
			p.push_back({tmp});
		}else{
			q.push_back(S[ind]);
			ind++;
		}
	}
}

void solve(string S);
// oddloop
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	string S;
	while(cin>>S,S!="#") solve(S);
}

void solve(string S){
	int x=0;
	cout<<f(S,x).size()<<"\n";
}
accuracy: 1
time_ms: 1240
memory_kb: 3416
final_rank: 4

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

int expr(string &s, int &i, int id, int &n, int &ng, vector<int> &o) {
	int res = 0;
	if(id == n) {
		if(s[i] == '(') {
			i++;
			res = expr(s, i, 0, n, ng, o);
			i++;
		} else {
			while(i < s.size() && isdigit(s[i])) {
				res = res * 10 + s[i] - '0';
				i++;
			}
		}
	} else {
		res = expr(s, i, id + 1, n, ng, o);
		while(true) {
			if(i < o.size() && o[i] == id) {
				char op = s[i];
				int to = expr(s, ++i, id + 1, n, ng, o);
				if(op == '+') res += to;
				if(op == '-') res -= to;
				if(op == '*') res *= to;
				if(op == '/') {
					if(to == 0) ng = 1;
					else res /= to;
				}
			} else break;
		}
	}
	return res;
}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	
	while(true) {
		string s; cin >> s; if(s == "#") break;
		int n = 0;
		vector<int> op;
		auto isop = [&](char c){ return c == '+' || c == '-' || c == '*' || c == '/'; };
		rep(i,s.size()) if(isop(s[i])) n++, op.push_back(i);

		vector<int> p(n), o(s.size(), -1);
		iota(p.begin(), p.end(), 0);
		set<int> ans;
		do {
			int pos = 0, ng = 0;
			vector<int> o(s.size(), -1);
			int j = 0;
			for(int i : op) o[i] = p[j++];
			int res = expr(s, pos, 0, n, ng, o);
			if(!ng) ans.insert(res);
		} while(next_permutation(p.begin(), p.end()));
		cout << ans.size() << endl;
	}
}
accuracy: 1
time_ms: 1450
memory_kb: 3472
final_rank: 9

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

int expr(string &s, int &i, int id, int &n, int &ng, vector<int> &o) {
	int res = 0;
	if(id == n) {
		if(s[i] == '(') {
			i++;
			res = expr(s, i, 0, n, ng, o);
			i++;
		} else {
			while(i < s.size() && isdigit(s[i])) {
				res = res * 10 + s[i] - '0';
				i++;
			}
		}
	} else {
		res = expr(s, i, id + 1, n, ng, o);
		while(true) {
			if(i < o.size() && o[i] == id) {
				char op = s[i];
				int to = expr(s, ++i, id + 1, n, ng, o);
				if(op == '+') res += to;
				if(op == '-') res -= to;
				if(op == '*') res *= to;
				if(op == '/') {
					if(to == 0) ng = 1;
					else res /= to;
				}
			} else break;
		}
	}
	return res;
}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	
	while(true) {
		string s; cin >> s; if(s == "#") break;
		int n = 0;
		auto isop = [&](char c){ return c == '+' || c == '-' || c == '*' || c == '/'; };
		rep(i,s.size()) if(isop(s[i])) n++;

		vector<int> p(n);
		iota(p.begin(), p.end(), 0);
		set<int> ans;
		do {
			int pos = 0, ng = 0;
			vector<int> o(s.size(), -1);
			int j = 0;
			rep(i,s.size()) if(isop(s[i])) o[i] = p[j++];
			int res = expr(s, pos, 0, n, ng, o);
			if(!ng) ans.insert(res);
		} while(next_permutation(p.begin(), p.end()));
		cout << ans.size() << endl;
	}
}
accuracy: 1
time_ms: 1620
memory_kb: 3388
final_rank: 8

code_snippet: #pragma region Macros
#pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2,tune=native")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,fma,abm,mmx,avx,avx2")
// #pragma GCC target("avx2")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#define ll long long
using ld = long double;
#define rep2(i, a, b) for(ll i = (a); i <= (b); i++)
#define rep3(i, a, b) for(ll i = (a); i >= (b); --i)
#define rep(i, n) for(ll i = 0; i < n; ++i)
#define each(i, a) for(auto &&i : a)
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define eb emplace_back
#define vi vector<int>
#define vll vector<ll>
#define vpi vector<pii>
#define vpll vector<pll>
#define overload2(_1, _2, name, ...) name
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define VEC(type, name, size)                                                                                                                                  \
    vector<type> name(size);                                                                                                                                   \
    IN(name)
#define VEC2(type, name1, name2, size)                                                                                                                         \
    vector<type> name1(size), name2(size);                                                                                                                     \
    for(int i = 0; i < size; i++) IN(name1[i], name2[i])
#define VEC3(type, name1, name2, name3, size)                                                                                                                  \
    vector<type> name1(size), name2(size), name3(size);                                                                                                        \
    for(int i = 0; i < size; i++) IN(name1[i], name2[i], name3[i])
#define vv(type, name, h, ...) vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define VV(type, name, h, w)                                                                                                                                   \
    vector<vector<type>> name(h, vector<type>(w));                                                                                                             \
    IN(name)
#define vvv(type, name, h, w, ...) vector<vector<vector<type>>> name(h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)                                                                                                                         \
    vector<vector<vector<vector<type>>>> name(a, vector<vector<vector<type>>>(b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define mt make_tuple
#define fi first
#define se second
#define all(c) begin(c), end(c)
#define rall(c) rbegin(c), rend(c)
#define SORT(v) sort(all(v))
#define REV(v) reverse(all(v))
template <class T = ll, class S> T SUM(const S &v) { return accumulate(all(v), T(0)); }
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
using namespace std;
constexpr pii dx4[4] = {pii{1, 0}, pii{0, 1}, pii{-1, 0}, pii{0, -1}};
constexpr pii dx8[8] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
const string YESNO[2] = {"NO", "YES"};
const string YesNo[2] = {"No", "Yes"};
const string yesno[2] = {"no", "yes"};
void YES(bool t = 1) { cout << YESNO[t] << endl; }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { cout << YesNo[t] << endl; }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { cout << yesno[t] << endl; }
void no(bool t = 1) { yes(!t); }
template <class T> using vc = vector<T>;
template <class T> using vvc = vector<vc<T>>;
template <class T> using vvvc = vector<vvc<T>>;
template <class T> using vvvvc = vector<vvvc<T>>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
#define si(c) (int)(c).size()
#define INT(...)                                                                                                                                               \
    int __VA_ARGS__;                                                                                                                                           \
    IN(__VA_ARGS__)
#define LL(...)                                                                                                                                                \
    ll __VA_ARGS__;                                                                                                                                            \
    IN(__VA_ARGS__)
#define STR(...)                                                                                                                                               \
    string __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
#define CHR(...)                                                                                                                                               \
    char __VA_ARGS__;                                                                                                                                          \
    IN(__VA_ARGS__)
#define DBL(...)                                                                                                                                               \
    double __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
int scan() { return getchar(); }
void scan(int &a) { cin >> a; }
void scan(long long &a) { cin >> a; }
void scan(char &a) { cin >> a; }
void scan(double &a) { cin >> a; }
void scan(string &a) { cin >> a; }
template <class T, class S> void scan(pair<T, S> &p) { scan(p.first), scan(p.second); }
template <class T> void scan(vector<T> &);
template <class T> void scan(vector<T> &a) {
    for(auto &i : a) scan(i);
}
template <class T> void scan(T &a) { cin >> a; }
void IN() {}
template <class Head, class... Tail> void IN(Head &head, Tail &...tail) {
    scan(head);
    IN(tail...);
}

template <class T, class S> inline bool chmax(T &a, const S &b) { return (a < b ? a = b, 1 : 0); }
template <class T, class S> inline bool chmin(T &a, const S &b) { return (a > b ? a = b, 1 : 0); }
vi iota(int n) {
    vi a(n);
    iota(all(a), 0);
    return a;
}
template <typename T> vi iota(vector<T> &a, bool greater = false) {
    vi res(a.size());
    iota(all(res), 0);
    sort(all(res), [&](int i, int j) {
        if(greater) return a[i] > a[j];
        return a[i] < a[j];
    });
    return res;
}
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

template <class T> T ceil(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? (x + y - 1) / y : x / y);
}

template <class T> T floor(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? x / y : (x + y - 1) / y);
}
template <class T> T POW(T x, int n) {
    T res = 1;
    for(; n; n >>= 1, x *= x)
        if(n & 1) res *= x;
    return res;
}
template <class T, class S> T POW(T x, S n, const ll &mod) {
    T res = 1;
    for(; n; n >>= 1, x = x * x % mod)
        if(n & 1) res = res * x % mod;
    return res;
}
vector<pll> factor(ll x) {
    vector<pll> ans;
    for(ll i = 2; i * i <= x; i++)
        if(x % i == 0) {
            ans.push_back({i, 1});
            while((x /= i) % i == 0) ans.back().second++;
        }
    if(x != 1) ans.push_back({x, 1});
    return ans;
}
template <class T> vector<T> divisor(T x) {
    vector<T> ans;
    for(T i = 1; i * i <= x; i++)
        if(x % i == 0) {
            ans.pb(i);
            if(i * i != x) ans.pb(x / i);
        }
    return ans;
}
template <typename T> void zip(vector<T> &x) {
    vector<T> y = x;
    UNIQUE(y);
    for(int i = 0; i < x.size(); ++i) { x[i] = lb(y, x[i]); }
}
template <class S> void fold_in(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void fold_in(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto e : a) v.emplace_back(e);
    fold_in(v, tail...);
}
template <class S> void renumber(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void renumber(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto &&e : a) e = lb(v, e);
    renumber(v, tail...);
}
template <class S, class... Args> vector<S> zip(vector<S> &head, Args &&...args) {
    vector<S> v;
    fold_in(v, head, args...);
    sort(all(v)), v.erase(unique(all(v)), v.end());
    renumber(v, head, args...);
    return v;
}

// x in [l, r)
template <class T, class S> bool inc(const T &x, const S &l, const S &r) { return l <= x and x < r; }
// (a, b) in [lx, rx) * [ly, ry)
template <class T, class S> bool inc(const pair<T, T> &x, const S &lx, const S &ly, const S &rx, const S &ry) { return inc(x.fi, lx, rx) && inc(x.se, ly, ry); }

constexpr ll ten(int n) { return n == 0 ? 1 : ten(n - 1) * 10; }
// bit 演算系
ll pow2(int i) { return 1LL << i; }
int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
int topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
int lowbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); }
int lowbit(ll a) { return a == 0 ? 64 : __builtin_ctzll(a); }
// int allbit(int n) { return (1 << n) - 1; }
constexpr ll allbit(int n) { return (1LL << n) - 1; }
// int popcount(signed t) { return __builtin_popcount(t); }
// int popcount(ll t) { return __builtin_popcountll(t); }
int popcount(uint64_t t) { return __builtin_popcountll(t); }
bool ispow2(int i) { return i && (i & -i) == i; }

ll rnd(ll l, ll r) { //[l, r)
#ifdef _LOCAL
    static mt19937_64 gen;
#else
    static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
#endif
    return uniform_int_distribution<ll>(l, r - 1)(gen);
}
ll rnd(ll n) { return rnd(0, n); }

template <class t> void random_shuffle(vc<t> &a) { rep(i, si(a)) swap(a[i], a[rnd(0, i + 1)]); }

int in() {
    int x;
    cin >> x;
    return x;
}
ll lin() {
    unsigned long long x;
    cin >> x;
    return x;
}

template <class T, class S> pair<T, S> operator-(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi - y.fi, x.se - y.se); }
template <class T, class S> pair<T, S> operator+(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi + y.fi, x.se + y.se); }
template <class T> pair<T, T> operator&(const pair<T, T> &l, const pair<T, T> &r) { return pair<T, T>(max(l.fi, r.fi), min(l.se, r.se)); }
template <class T, class S> pair<T, S> operator+=(pair<T, S> &l, const pair<T, S> &r) { return l = l + r; }
template <class T, class S> pair<T, S> operator-=(pair<T, S> &l, const pair<T, S> &r) { return l = l - r; }
template <class T> bool intersect(const pair<T, T> &l, const pair<T, T> &r) { return (l.se < r.se ? r.fi < l.se : l.fi < r.se); }

template <class T> ll operator*(const pair<T, T> &x, const pair<T, T> &y) { return (ll)x.fi * y.fi + (ll)x.se * y.se; }

template <typename T> struct edge {
    int from, to;
    T cost;
    int id;
    edge(int to, T cost) : from(-1), to(to), cost(cost) {}
    edge(int from, int to, T cost) : from(from), to(to), cost(cost) {}
    edge(int from, int to, T cost, int id) : from(from), to(to), cost(cost), id(id) {}
    constexpr bool operator<(const edge<T> &rhs) const noexcept { return cost < rhs.cost; }
    edge &operator=(const int &x) {
        to = x;
        return *this;
    }
    operator int() const { return to; }
};
template <typename T> using Edges = vector<edge<T>>;

using Tree = vector<vector<int>>;
using Graph = vector<vector<int>>;
template <class T> using Wgraph = vector<vector<edge<T>>>;
Graph getG(int n, int m = -1, bool directed = false, int margin = 1) {
    Tree res(n);
    if(m == -1) m = n - 1;
    while(m--) {
        int a, b;
        cin >> a >> b;
        a -= margin, b -= margin;
        res[a].emplace_back(b);
        if(!directed) res[b].emplace_back(a);
    }
    return res;
}
Graph getTreeFromPar(int n, int margin = 1) {
    Graph res(n);
    for(int i = 1; i < n; i++) {
        int a;
        cin >> a;
        res[a - margin].emplace_back(i);
    }
    return res;
}
template <class T> Wgraph<T> getWg(int n, int m = -1, bool directed = false, int margin = 1) {
    Wgraph<T> res(n);
    if(m == -1) m = n - 1;
    while(m--) {
        int a, b;
        T c;
        cin >> a >> b >> c;
        a -= margin, b -= margin;
        res[a].emplace_back(b, c);
        if(!directed) res[b].emplace_back(a, c);
    }
    return res;
}
void add(Graph &G, int x, int y) { G[x].eb(y), G[y].eb(x); }
template <class S, class T> void add(Wgraph<S> &G, int x, int y, T c) { G[x].eb(y, c), G[y].eb(x, c); }

#define i128 __int128_t
#define ull unsigned long long int
#define TEST                                                                                                                                                   \
    INT(testcases);                                                                                                                                            \
    while(testcases--)
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    for(auto it = begin(v); it != end(v); ++it) {
        if(it == begin(v))
            os << *it;
        else
            os << " " << *it;
    }
    return os;
}
template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {
    os << p.first << " " << p.second;
    return os;
}
template <class S, class T> string to_string(pair<S, T> p) { return "(" + to_string(p.first) + "," + to_string(p.second) + ")"; }
string to_string(string s) { return "\"" + s + "\""; }
string to_string(char c) { return string(1, c); }
template <class T> string to_string(vector<T> s) {
    string res = "{";
    for(auto it = s.begin(); it != s.end(); it++) res += to_string(*it) + (next(it) == s.end() ? "" : ", ");
    return res + "}";
}
template <class T> string to_string(set<T> s) {
    string res = "{";
    for(auto it = s.begin(); it != s.end(); it++) res += to_string(*it), res += (next(it) == end(s) ? "" : ", ");
    return res + "}";
}

#define endl '\n'

#ifdef _LOCAL
void dump() { cerr << endl; }
template <class Head, class... Tail> void dump(Head head, Tail... tail) {
    cerr << to_string(head) << " ";
    dump(tail...);
}
#undef endl
#define debug(x)                                                                                                                                               \
    cout << #x << ": ";                                                                                                                                        \
    dump(x)
#else
void dump() {}
template <class Head, class... Tail> void dump(Head head, Tail... tail) {}
#define debug(x)
#endif
template <class T> void print(const T &a) { cout << a; }
void OUT() { cout << endl; }
template <class Head, class... Tail> void OUT(const Head &head, const Tail &...tail) {
    print(head);
    if(sizeof...(tail)) cout << ' ';
    OUT(tail...);
}

template <typename T> static constexpr T inf = numeric_limits<T>::max() / 2;
#define drop(s) cout << #s << endl, exit(0)

template <int N> struct ndFORarray {
    std::array<int, N> v;
    ndFORarray(std::array<int, N> v_) : v(v_) {}
    struct ndFORitr {
        const std::array<int, N> &v;
        std::array<int, N> tmp;
        bool is_end;
        ndFORitr(const std::array<int, N> &v_) : v(v_), tmp(), is_end(false) {}
        bool operator!=(const ndFORitr &) const { return !is_end; }
        void operator++() {
            int pos = N - 1;
            while(pos != -1) {
                tmp[pos] += 1;
                if(tmp[pos] == v[pos]) {
                    tmp[pos] = 0;
                    pos -= 1;
                } else {
                    break;
                }
            }
            if(pos == -1) { is_end = true; }
        }
        const std::array<int, N> &operator*() const { return tmp; }
    };
    ndFORitr begin() const { return ndFORitr(v); }
    ndFORitr end() const { return ndFORitr(v); }
};

struct ndFORvector {
    std::vector<int> v;
    ndFORvector(std::vector<int> v_) : v(v_) {}
    struct ndFORitr {
        const std::vector<int> &v;
        std::vector<int> tmp;
        bool is_end;
        ndFORitr(const std::vector<int> &v_) : v(v_), tmp(v.size(), 0), is_end(false) {}
        bool operator!=(const ndFORitr &) const { return !is_end; }
        void operator++() {
            int pos = v.size() - 1;
            while(pos != -1) {
                tmp[pos] += 1;
                if(tmp[pos] == v[pos]) {
                    tmp[pos] = 0;
                    pos -= 1;
                } else {
                    break;
                }
            }
            if(pos == -1) { is_end = true; }
        }
        const std::vector<int> &operator*() const { return tmp; }
    };
    ndFORitr begin() const { return ndFORitr(v); }
    ndFORitr end() const { return ndFORitr(v); }
};

auto ndFOR(std::vector<int> v) { return ndFORvector(v); }
template <class... Ts> auto ndFOR(Ts... v) { return ndFORarray<std::tuple_size<std::tuple<Ts...>>::value>({v...}); }
template <class F> struct REC {
    F f;
    REC(F &&f_) : f(std::forward<F>(f_)) {}
    template <class... Args> auto operator()(Args &&...args) const { return f(*this, std::forward<Args>(args)...); }
};

template <class S> vector<pair<S, int>> runLength(const vector<S> &v) {
    vector<pair<S, int>> res;
    for(auto &e : v) {
        if(res.empty() or res.back().fi != e)
            res.eb(e, 1);
        else
            res.back().se++;
    }
    return res;
}
vector<pair<char, int>> runLength(const string &v) {
    vector<pair<char, int>> res;
    for(auto &e : v) {
        if(res.empty() or res.back().fi != e)
            res.eb(e, 1);
        else
            res.back().se++;
    }
    return res;
}

template <class T = int> struct Imos {
    int n;
    vector<T> a;
    Imos(int _n) : n(_n), a(_n + 1) {}
    void add(int l, int r, T val = 1) {
        if(l >= r) return;
        l = clamp(l, 0, n);
        r = clamp(r, 0, n + 1);
        a[l] += val;
        if(r <= n) a[r] -= val;
    }
    void build() {
        for(int i = 0; i < n; i++) a[i + 1] += a[i];
    }
    const T &operator[](int k) { return a[k]; }
};

template <class T> struct RUI {
    vector<T> a;
    RUI(const vector<T> &v) : a(v.size() + 1) {
        for(int i = 0; i < v.size(); i++) a[i + 1] = a[i] + v[i];
    }
    T get(int l, int r) { return a[r] - a[l]; }
};

template <class T, class F> T bin_search(T ok, T ng, const F &f) {
    while(abs(ok - ng) > 1) {
        T mid = ok + ng >> 1;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
template <class T, class F> T bin_search_double(T ok, T ng, const F &f, int iter = 80) {
    while(iter--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

struct Setup_io {
    Setup_io() {
        ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
        cout << fixed << setprecision(15);
    }
} setup_io;
#pragma endregion

vi id;
string s;
bool flag;
int calc(int x, char c, int y) {
    if(c == '+') return x + y;
    if(c == '-') return x - y;
    if(c == '*') return x * y;
    if(c == '/') {
        if(y == 0) return flag = false, 0;
        return x / y;
    }
    assert(0);
}
int eval(int &i, int p) {
    int x = 0;
    if(s[i] == '(') {
        i++;
        int res = eval(i, inf<int>);
        assert(s[i] == ')');
        x = res;
        i++;
    } else {
        while(i < si(s) and isdigit(s[i])) x = x * 10 + (s[i++] - '0');
    }
    while(1) {
        if(i == si(s) or s[i] == ')') return x;
        char c = s[i];
        int q = id[i];
        if(q < p) {
            i++;
            int y = eval(i, q);
            x = calc(x, c, y);
        } else {
            return x;
        }
    }
}

int main() {
    while(1) {
        cin >> s;
        if(s == "#") exit(0);

        int n = si(s);
        vi v;
        rep(i, n) {
            if(s[i] == '+' or s[i] == '-' or s[i] == '*' or s[i] == '/') v.eb(i);
        }
        id.resize(n);
        set<int> ans;
        do {
            rep(i, si(v)) id[v[i]] = i;
            int i = 0;
            flag = true;
            int res = eval(i, inf<int>);
            if(flag) ans.emplace(res);
        } while(next_permutation(all(v)));
        OUT(si(ans));
    }
}
accuracy: 1
time_ms: 460
memory_kb: 3528
final_rank: 2

code_snippet: // I SELL YOU...! 
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<queue>
#include<chrono>
#include<iomanip>
#include<map>
#include<set>
using namespace std;
using ll = int;
using P = pair<ll,ll>;
using TP = tuple<ll,ll,ll>;
void init_io(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(18);
}
const ll MAX = 11;
ll calc_digit(ll &idx, const string &s) {
  ll res = 0;
  ll n = s.size();
  while(idx < n && '0' <= s[idx] && s[idx] <= '9') {
    res = res * 10 + (s[idx] - '0');
    idx++;
  }
  return res;
}
ll calc_expr(ll &idx,ll t, const string &s,const vector<ll> &prior) {
  ll n = s.size();
  if (idx > n) return 0;
  if (t < (ll)prior.size()){
    ll t0 = calc_expr(idx, t+1, s, prior);
    if (idx == prior[t]) {
      char c = s[idx];
      idx++;
      ll t1 = calc_expr(idx, t+1, s, prior);
      switch(c) {
        case '+': t0 += t1; break;
        case '-': t0 -= t1; break;
        case '*': t0 *= t1; break;
        case '/': if (t1 == 0) {
                    idx = 2*n;
                  } else {
                    t0 /= t1; break;
                  }
      }
    }
    return t0;
  } else if (s[idx] == '(') {
    idx++;
    ll res = calc_expr(idx, 0, s, prior);
    idx++;
    return res;
  } else {
    return calc_digit(idx, s);
  }
}
void solve() {
  string s;
  cin >> s;
  if (s == "#") return;
  vector<ll> prior;
  ll n = s.size();
  for(int i=0;i<n;i++) {
    if (s[i] == '+' || s[i] =='-' || s[i] == '*' || s[i] == '/') {
      prior.push_back(i);
    }
  }
  set<ll> st;
  do {
    ll idx = 0;
    ll v = calc_expr(idx, 0, s, prior);
    if (idx == n) {
      st.insert(v);
    }
  }while(next_permutation(prior.begin(), prior.end()));
  cout << st.size() << endl;
  solve();
}
signed main(){
  init_io();
  solve();
}
accuracy: 1
time_ms: 1110
memory_kb: 3496
final_rank: 5

code_snippet: // #pragma comment(linker, "/stack:200000000")

#include <bits/stdc++.h>

#include <limits>
#include <type_traits>

namespace suisen {
// ! utility
template <typename ...Types>
using constraints_t = std::enable_if_t<std::conjunction_v<Types...>, std::nullptr_t>;
template <bool cond_v, typename Then, typename OrElse>
constexpr decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// ! function
template <typename ReturnType, typename Callable, typename ...Args>
using is_same_as_invoke_result = std::is_same<std::invoke_result_t<Callable, Args...>, ReturnType>;
template <typename F, typename T>
using is_uni_op = is_same_as_invoke_result<T, F, T>;
template <typename F, typename T>
using is_bin_op = is_same_as_invoke_result<T, F, T, T>;

template <typename Comparator, typename T>
using is_comparator = std::is_same<std::invoke_result_t<Comparator, T, T>, bool>;

// ! integral
template <typename T, typename = constraints_t<std::is_integral<T>>>
constexpr int bit_num = std::numeric_limits<std::make_unsigned_t<T>>::digits;
template <typename T, unsigned int n>
struct is_nbit { static constexpr bool value = bit_num<T> == n; };
template <typename T, unsigned int n>
static constexpr bool is_nbit_v = is_nbit<T, n>::value;

// ?
template <typename T>
struct safely_multipliable {};
template <>
struct safely_multipliable<int> { using type = long long; };
template <>
struct safely_multipliable<long long> { using type = __int128_t; };
template <>
struct safely_multipliable<float> { using type = float; };
template <>
struct safely_multipliable<double> { using type = double; };
template <>
struct safely_multipliable<long double> { using type = long double; };
template <typename T>
using safely_multipliable_t = typename safely_multipliable<T>::type;

} // namespace suisen

// ! type aliases
using i128 = __int128_t;
using u128 = __uint128_t;
using ll = long long;
using uint = unsigned int;
using ull  = unsigned long long;

template <typename T> using vec  = std::vector<T>;
template <typename T> using vec2 = vec<vec <T>>;
template <typename T> using vec3 = vec<vec2<T>>;
template <typename T> using vec4 = vec<vec3<T>>;

template <typename T>
using pq_greater = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <typename T, typename U>
using umap = std::unordered_map<T, U>;

// ! macros (capital: internal macro)
#define OVERLOAD2(_1,_2,name,...) name
#define OVERLOAD3(_1,_2,_3,name,...) name
#define OVERLOAD4(_1,_2,_3,_4,name,...) name

#define REP4(i,l,r,s)  for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l);i<(r);i+=(s))
#define REP3(i,l,r)    REP4(i,l,r,1)
#define REP2(i,n)      REP3(i,0,n)
#define REPINF3(i,l,s) for(std::remove_reference_t<std::remove_const_t<decltype(l)>>i=(l);;i+=(s))
#define REPINF2(i,l)   REPINF3(i,l,1)
#define REPINF1(i)     REPINF2(i,0)
#define RREP4(i,l,r,s) for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l)+fld((r)-(l)-1,s)*(s);i>=(l);i-=(s))
#define RREP3(i,l,r)   RREP4(i,l,r,1)
#define RREP2(i,n)     RREP3(i,0,n)

#define rep(...)    OVERLOAD4(__VA_ARGS__, REP4   , REP3   , REP2   )(__VA_ARGS__)
#define rrep(...)   OVERLOAD4(__VA_ARGS__, RREP4  , RREP3  , RREP2  )(__VA_ARGS__)
#define repinf(...) OVERLOAD3(__VA_ARGS__, REPINF3, REPINF2, REPINF1)(__VA_ARGS__)

#define CAT_I(a, b) a##b
#define CAT(a, b) CAT_I(a, b)
#define UNIQVAR(tag) CAT(tag, __LINE__)
#define loop(n) for (std::remove_reference_t<std::remove_const_t<decltype(n)>> UNIQVAR(loop_variable) = n; UNIQVAR(loop_variable) --> 0;)

#define all(iterable) (iterable).begin(), (iterable).end()
#define input(type, ...) type __VA_ARGS__; read(__VA_ARGS__)

// ! I/O utilities

// pair
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U> &a) {
    return out << a.first << ' ' << a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return out;
    } else {
        out << std::get<N>(a);
        if constexpr (N + 1 < std::tuple_size_v<std::tuple<Args...>>) {
            out << ' ';
        }
        return operator<<<N + 1>(out, a);
    }
}
// vector
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
inline void print() { std::cout << '\n'; }
template <typename Head, typename... Tail>
inline void print(const Head &head, const Tail &...tails) {
    std::cout << head;
    if (sizeof...(tails)) std::cout << ' ';
    print(tails...);
}
template <typename Iterable>
auto print_all(const Iterable& v, std::string sep = " ", std::string end = "\n") -> decltype(std::cout << *v.begin(), void()) {
    for (auto it = v.begin(); it != v.end();) {
        std::cout << *it;
        if (++it != v.end()) std::cout << sep;
    }
    std::cout << end;
}

// pair
template <typename T, typename U>
std::istream& operator>>(std::istream& in, std::pair<T, U> &a) {
    return in >> a.first >> a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return in;
    } else {
        return operator>><N + 1>(in >> std::get<N>(a), a);
    }
}
// vector
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
template <typename ...Args>
void read(Args &...args) {
    ( std::cin >> ... >> args );
}

// ! integral utilities

// Returns pow(-1, n)
template <typename T>
constexpr inline int pow_m1(T n) {
    return -(n & 1) | 1;
}
// Returns pow(-1, n)
template <>
constexpr inline int pow_m1<bool>(bool n) {
    return -int(n) | 1;
}

// Returns floor(x / y)
template <typename T>
constexpr inline T fld(const T x, const T y) {
    return (x ^ y) >= 0 ? x / y : (x - (y + pow_m1(y >= 0))) / y;
}
template <typename T>
constexpr inline T cld(const T x, const T y) {
    return (x ^ y) <= 0 ? x / y : (x + (y + pow_m1(y >= 0))) / y;
}

template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcount(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcountll(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clzll(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctzll(x) : suisen::bit_num<T>; }
template <typename T>
constexpr inline int floor_log2(const T x) { return suisen::bit_num<T> - 1 - count_lz(x); }
template <typename T>
constexpr inline int ceil_log2(const T x)  { return floor_log2(x) + ((x & -x) != x); }
template <typename T>
constexpr inline int kth_bit(const T x, const unsigned int k) { return (x >> k) & 1; }
template <typename T>
constexpr inline int parity(const T x) { return popcount(x) & 1; }

struct all_subset {
    struct all_subset_iter {
        const int s; int t;
        constexpr all_subset_iter(int s) : s(s), t(s + 1) {}
        constexpr auto operator*() const { return t; }
        constexpr auto operator++() {}
        constexpr auto operator!=(std::nullptr_t) { return t ? (--t &= s, true) : false; }
    };
    int s;
    constexpr all_subset(int s) : s(s) {}
    constexpr auto begin() { return all_subset_iter(s); }
    constexpr auto end()   { return nullptr; }
};

// ! container

template <typename T, typename Comparator, suisen::constraints_t<suisen::is_comparator<Comparator, T>> = nullptr>
auto priqueue_comp(const Comparator comparator) {
    return std::priority_queue<T, std::vector<T>, Comparator>(comparator);
}

template <typename Iterable>
auto isize(const Iterable &iterable) -> decltype(int(iterable.size())) {
    return iterable.size();
}

template <typename T, typename Gen, suisen::constraints_t<suisen::is_same_as_invoke_result<T, Gen, int>> = nullptr>
auto generate_vector(int n, Gen generator) {
    std::vector<T> v(n);
    for (int i = 0; i < n; ++i) v[i] = generator(i);
    return v;
}

template <typename T>
void sort_unique_erase(std::vector<T> &a) {
    std::sort(a.begin(), a.end());
    a.erase(std::unique(a.begin(), a.end()), a.end());
}

// ! other utilities

// x <- min(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmin(T &x, const T &y) {
    if (y >= x) return false;
    x = y;
    return true;
}
// x <- max(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmax(T &x, const T &y) {
    if (y <= x) return false;
    x = y;
    return true;
}

namespace suisen {}
using namespace suisen;
using namespace std;

struct io_setup {
    io_setup(int precision = 20) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(precision);
    }
} io_setup_ {};

// ! code from here

bool is_digit(char c) {
    return '0' <= c and c <= '9';
}

pair<int, int> num(const string &expr, int l) {
    int n = expr.size();
    int r = l;
    while (r < n and is_digit(expr[r])) ++r;
    return { r, stoi(expr.substr(l, r - l)) };
}

pair<int, set<int>> eval(const string &expr, int l) {
    const int n = expr.size();
    vector<set<int>> sets;
    vector<char> ops;
    while (true) {
        if (expr[l] == '(') {
            auto [nl, st] = eval(expr, l + 1);
            assert(expr[nl] == ')');
            sets.push_back(move(st));
            l = nl + 1;
        } else if (is_digit(expr[l])) {
            auto [nl, val] = num(expr, l);
            sets.push_back(set<int> { val });
            l = nl;
        }
        if (l == n or expr[l] == ')') break;
        ops.push_back(expr[l++]);
    }
    auto dfs = [&](auto dfs, vector<set<int>> &vals, vector<char> &ops) -> set<int> {
        int t = vals.size();
        if (t == 1) return vals[0];
        set<int> res;
        rep(i, t - 1) {
            set<int> st;
            char op = ops[i];
            auto sl = move(vals[i]), sr = move(vals[i + 1]);
            for (int lhs : sl) for (int rhs : sr) {
                if (op == '+') {
                    st.insert(lhs + rhs);
                } else if (op == '-') {
                    st.insert(lhs - rhs);
                } else if (op == '*') {
                    st.insert(lhs * rhs);
                } else if (op == '/') {
                    if (rhs != 0) st.insert(lhs / rhs);
                } else assert(false);
            }
            ops.erase(ops.begin() + i);
            vals.erase(vals.begin() + i + 1);
            vals.erase(vals.begin() + i);
            vals.insert(vals.begin() + i, move(st));
            res.merge(dfs(dfs, vals, ops));
            vals.erase(vals.begin() + i);
            vals.insert(vals.begin() + i, move(sl));
            vals.insert(vals.begin() + i + 1, move(sr));
            ops.insert(ops.begin() + i, op);
        }
        return res;
    };
    return { l, dfs(dfs, sets, ops) };
}

int main() {
    while (true) {
        input(string, expr);
        if (expr == "#") break;
        print(eval(expr, 0).second.size());
    }
}
accuracy: 1
time_ms: 670
memory_kb: 3348
final_rank: 1

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

using namespace std;

using ll = long long;
using State = string::const_iterator;
class ParseError {};
constexpr ll MOD = 1e9 + 7;
constexpr ll INF = 1e18;

// 四則演算の式をパースして、その評価結果を返す。
set<int> expression(State &begin);

set<int> factor(State &begin);
// 数字の列をパースして、その数を返す。
set<int> number(State &begin);

set<int> solve(vector<set<int>> vv, vector<char> op) {
    if(op.empty()) return vv[0];
    set<int> st;
    for(int i = 0; i < op.size(); i++) {
        auto cpvv = vv;
        auto cpop = op;
        function<int(int,int)> fnc;
        if(cpop[i] == '+') {
            fnc = [](int a, int b) { return a + b; };
        } else if(cpop[i] == '-') {
            fnc = [](int a, int b) { return a - b; };
        } else if(cpop[i] == '*') {
            fnc = [](int a, int b) { return a * b; };
        } else if(cpop[i] == '/') {
            fnc = [](int a, int b) { return a / b; };
        }

        set<int> ret;
        for(auto x : cpvv[i]) {
            for(auto y : cpvv[i + 1]) {
                if(!(cpop[i]=='/'&&y==0))ret.insert(fnc(x, y));
            }
        }
        cpvv[i] = ret;
        cpvv.erase(cpvv.begin() + i + 1);
        cpop.erase(cpop.begin() + i);
        auto sol = solve(cpvv, cpop);
        for(auto x:sol)st.insert(x);
    }
    return st;
}

// 数字の列をパースして，その数を返す
set<int> number(State &begin) {
    int ret = 0;
    while(isdigit(*begin)) {
        ret *= 10;
        ret += *begin - '0';
        begin++;
    }
    set<int> v;
    v.insert(ret);
    return v;
}

// カッコを先に計算
set<int> factor(State &begin) {
    if(*begin == '(') {
        begin++;
        set<int> ret = expression(begin);
        begin++; // ')' を飛ばす
        return ret;
    } else {
        return number(begin);
    }
}

// 四則演算の式をパースして，結果を返す
set<int> expression(State &begin) {
    vector<set<int>> vv; // 6/2*(1+2) -> [{6},{2},{3}]
    set<int> ret = factor(begin);
    vv.push_back(ret);
    vector<char> op;
    for(;;) {
        if(*begin == '+') {
            begin++;
            op.push_back('+');
            vv.push_back(factor(begin));
        } else if(*begin == '-') {
            begin++;
            op.push_back('-');
            vv.push_back(factor(begin));
        } else if(*begin == '*') {
            begin++;
            op.push_back('*');
            vv.push_back(factor(begin));
        } else if(*begin == '/') {
            begin++;
            op.push_back('/');
            vv.push_back(factor(begin));
        }else {
            break;
        }
    }
    set<int> sol = solve(vv, op);
    return sol;
}

// 乗算除算の式をパースして，その結果を返す
// int term(State &begin){
//     int ret = factor(begin);
//     for(;;){
//         if(*begin == '*'){
//             begin++;
//             ret *= factor(begin);
//         }else if(*begin == '/'){
//             begin++;
//             ret /= factor(begin);
//         }else{
//             break;
//         }
//     }
//     return ret;
// }

int main() {
    string s;
    while(1) {
        cin >> s;
        if(s == "#") break;
        State begin = s.begin();
        cout << expression(begin).size() << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 1870
memory_kb: 3456
final_rank: 10