Problem: Count the maximum number of ways we can parenthesize of a given boolean expression so that the value of expression evaluates to true or false as asked.
Boolean expression will be given with following symbols.
Symbols
‘T’ —> true
‘F’ —> false
And the Operators
& —> boolean AND
| —> boolean OR
^ —> boolean XOR
The appears as Interview question in Microsoft & Amazon.
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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
#include <iostream> #include <string> using namespace std; int T[105][105]; int F[105][105]; int main() { //code int t,n; string s,str,op; cin>>t; while(t--) { cin>>n; cin>>str; s=""; op=""; for(int i=0;i<str.size();i++) { if(i%2==0) s+=str[i]; else op+=str[i]; } for(int i=0;i<105;i++) { for(int j=0;j<105;j++) { T[i][j]=0; F[i][j]=0; } } for(int i=0;i<s.size();i++) { if(s[i]=='T') T[i][1]=1; else F[i][1]=1; } for(int len=2;len<=s.size();len++) { for(int i=0;i+len-1<s.size();i++) { for(int k=1;k<=len;k++) { if(op[i+k-1]=='&') { T[i][len]= (T[i][len] + T[i][k]*T[i+k][len-k])%1003; F[i][len]= (F[i][len] + F[i][k]*F[i+k][len-k])%1003; F[i][len]= (F[i][len] + F[i][k]*T[i+k][len-k])%1003; F[i][len]= (F[i][len] + T[i][k]*F[i+k][len-k])%1003; } if(op[i+k-1]=='^') { T[i][len]= (T[i][len] + F[i][k]*T[i+k][len-k])%1003; T[i][len]= (T[i][len] + T[i][k]*F[i+k][len-k])%1003; F[i][len]= (F[i][len] + F[i][k]*F[i+k][len-k])%1003; F[i][len]= (F[i][len] + T[i][k]*T[i+k][len-k])%1003; } if(op[i+k-1]=='|') { F[i][len]= (F[i][len] + F[i][k]*F[i+k][len-k])%1003; T[i][len]= (T[i][len] + T[i][k]*T[i+k][len-k])%1003; T[i][len]= (T[i][len] + F[i][k]*T[i+k][len-k])%1003; T[i][len]= (T[i][len] + T[i][k]*F[i+k][len-k])%1003; } } } } //cout<<s<<" "<<op<<endl; cout<<T[0][s.size()]<<endl; } return 0; } |