首先一开始我是打算进行暴力的,而且一开始也没注意时间复杂度。先贴上暴力代码(30分)
Code(30分):
#include<bits/stdc++.h>
using namespace std;
stack<int> stk;
string s;
int a[100010];
int x,y;
int main(){
getline(cin,s);
int n;
cin >> n;
for(int i=1;i<=n;i++){
cin >> a[i];
}
// for(int i=1; i<=n; i++){
// cout <<i << ' ' << a[i] << endl;
// }
int q;
cin >> q;
while(q--){
int t;
cin >> t;
a[t]=!a[t];
for(int i=0;i<s.size();i++){
if(s[i]=='x'){
int mle=i+1;
string temp;
while(s[mle]>='0'&&s[mle]<='9'){
temp += s[mle];
mle++;
}
i = mle;
int x1 = stoll(temp);
stk.push(a[x1]);
// cout << "add: "<< x << ' ' << a[x1] << endl;
x1++;
}
if(s[i]=='&'){
x=stk.top();
stk.pop();
y=stk.top();
stk.pop();
stk.push(x&y);
// cout << " --- " << x <<' ' << y << endl;
}
else if(s[i]=='|'){
x=stk.top();
stk.pop();
y=stk.top();
stk.pop();
stk.push(x|y);
// cout << " ||| " << x <<' ' << y << endl;
}
else if(s[i]=='!'){
x=stk.top();
stk.pop();
stk.push(!x);
}
// cout << i << ' ' << stk.top()<<endl;
}
cout<<stk.top() << endl;
a[t]=!a[t];
}
return 0;
}
然后就TLE了,所以我们需要新的方法,表达式树。思路见下图:
有了思路就不难了
AC code
#include <bits/stdc++.h>
using namespace std;
stack<int> stk;
struct point{
int n, x;
char c;
int left, right;
};
point pont[1000005];
int p, n, x[100005];
bool bian[100005];
bool yu[2][2][2], huo[2][2][2];
void dfs(int r) {
if(pont[r].left == 0 && pont[r].right == 0){
bian[pont[r].x] = true;
return;
}
int ln = pont[pont[r].left].n, rn = pont[pont[r].right].n;
if(pont[r].c == '&'){
if(yu[ln][rn][0]){
dfs(pont[r].left);
}
if(yu[ln][rn][1]){
dfs(pont[r].right);
}
}
else if(pont[r].c == '|'){
if(huo[ln][rn][0]){
dfs(pont[r].left);
}
if(huo[ln][rn][1]){
dfs(pont[r].right);
}
}
else{
dfs(pont[r].right);
}
}
int main(){
for(int i = 0; i <= 1; i++){
for(int j = 0; j <= 1; j++){
yu[i][j][0] = (i && j) != (!i && j);
yu[i][j][1] = (i && j) != (i && !j);
huo[i][j][0] = (i || j) != (!i || j);
huo[i][j][1] = (i || j) != (i || !j);
}
}
string s;
int num = 0, q, j;
getline(cin, s);
cin >> n;
for(int i=1;i<=n;i++){
cin >> x[i];
}
for(int i=0;i<s.length();i++){
if(s[i] == 'x'){
continue;
}
else if(s[i] >= '0' && s[i] <= '9'){
num = num*10+s[i]-'0';
}
else if(s[i] == ' '){
if(num > 0){
int np = p++;
pont[np].n = x[num];
pont[np].x = num;
stk.push(np);
num = 0;
}
}
else{
int np = p++;
pont[np].c = s[i];
pont[np].right = stk.top();
stk.pop();
if(s[i] == '!'){
pont[np].n = !pont[pont[np].right].n;
}
else{
pont[np].left = stk.top();
stk.pop();
if(s[i] == '&'){
pont[np].n = pont[pont[np].left].n && pont[pont[np].right].n;
}
else{
pont[np].n = pont[pont[np].left].n || pont[pont[np].right].n;
}
}
stk.push(np);
}
}
int gen = stk.top(),val = pont[gen].n;
dfs(gen);
cin >> q;
while(q--){
cin >> j;
if(bian[j]){
cout << !val << endl;
}
else{
cout << val << endl;
}
}
return 0;
}