AOJ1155 How Can I Satisfy Thee? Let Me Count the Ways...

How can I satisfy thee? Let me count the ways... | Aizu Online Judge

Introduction to Programming Introduction to Algorithms and Data Structures Library of Data Structures Library of Graph Algorithms Library of Computational Geometry Library of Dynamic Programming Library of Number Theory

構文解析.

の場合に分けて考える.入れ子の括弧にどう対応させるかよく分からなかったが,自分なりに理解することができた.構文解析の関数が出来たら,の組み合わせ(通り)を全列挙して, となる個数を数える.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int formula(string& s, int& i) {
  if(s[i] == '(') {
      i++;
      int val = formula(s, i);

      char op = s[i];

      i++;
      int val2 = formula(s, i);

      int ret = 0;
      if(op == '+') {
          if(val == 2 || val2 == 2) ret = 2;
          else if(val == 1 || val2 == 1) ret = 1;
          else ret = 0;
      }
      if(op == '*') {
          if(val == 2 && val2 == 2) ret = 2;
          else if((val == 1 || val == 2) && (val2 == 1 || val2 == 2)) ret = 1;
          else ret = 0;
      }

      i++;
      return ret;
  } else if(isdigit(s[i])) {
      int ret = (s[i] - '0');
      i++;
      return ret;
  } else if(s[i] == '-') {
      i++;
      int val = formula(s, i);

      int ret = 0;
      if(val == 0) ret = 2;
      if(val == 1) ret = 1;
      if(val == 2) ret = 0;

      return ret;
  }
}


int main() {
  string s;
  while(cin >> s) {
      if(s == ".") break;

      int ans = 0;
      rep(i, 3) {
          rep(j, 3) {
              rep(k, 3) {
                  string t = s;
                  rep(l, s.size()) {
                      if(t[l] == 'P') t[l] = ('0' + i);
                      else if(t[l] == 'Q') t[l] = ('0' + j);
                      else if(t[l] == 'R') t[l] = ('0' + k);
                  }

                  int p = 0;
                  if(formula(t, p) == 2) {
                      ans++;
                  }
              }
          }
      }

      cout << ans << endl;
  }

  return 0;
}
May 20th, 2016