-
Notifications
You must be signed in to change notification settings - Fork 0
/
Boolean_Parenthesization.cpp
40 lines (31 loc) · 1.44 KB
/
Boolean_Parenthesization.cpp
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
class Solution {
public:
const long long MOD = 1003;
pair<int, int> dfs(string& s, int low, int high, vector<vector<pair<int, int>>>& dp) {
if (low == high) {
if (s[low] == 'T') return {1, 0};
else return {0, 1};
}
if (dp[low][high] != make_pair(-1, -1)) return dp[low][high];
long long truth = 0, falsy = 0;
for (int i = low; i < high; i += 2) {
auto left = dfs(s, low, i, dp);
auto right = dfs(s, i + 2, high, dp);
if (s[i + 1] == '|') {
truth = (truth + (left.first * right.first + left.first * right.second + left.second * right.first) % MOD) % MOD;
falsy = (falsy + left.second * right.second) % MOD;
} else if (s[i + 1] == '&') {
truth = (truth + left.first * right.first) % MOD;
falsy = (falsy + (left.first * right.second + left.second * right.first + left.second * right.second) % MOD) % MOD;
} else {
truth = (truth + (left.first * right.second + left.second * right.first) % MOD) % MOD;
falsy = (falsy + (left.first * right.first + left.second * right.second) % MOD) % MOD;
}
}
return dp[low][high] = {truth, falsy};
}
int countWays(int n, string s) {
vector<vector<pair<int, int>>> dp(n, vector<pair<int, int>>(n, {-1, -1}));
return dfs(s, 0, n - 1, dp).first;
}
};