思路: 1、建树 2、计算结果 3、分析每个变量会不会影响结果 4、直接打表输出
#include<bits/stdc++.h>
using namespace std;
#define maxn 100005
struct node{
char op;
int no;
bool val;
node *lc;
node *rc;
node(char _op,int _no,bool _val):op(_op),no(_no),val(_val),lc(NULL),rc(NULL){};
}*root;
node *leaf[maxn];
bool table[maxn],x;
int n,q,qi;
string s;
stack<node *> st;
void crtree(){
int k;
for(int i=0;i<s.length();i++){
if(s[i]=='x'){
k=0;
while(s[i+1]>='0' && s[i+1]<='9'){
i++;
k=k*10+s[i]-'0';
}
node *nd=new node('x',k,0);
st.push(nd);
leaf[k]=nd;
//cout<<s[i]<<' '<<k<<' ';
}else if(s[i]=='!'){
node *nd=new node('!',0,0);
nd->lc=st.top();
st.pop();
st.push(nd);
}else if(s[i]=='&'||s[i]=='|'){
node *nd=new node(s[i],0,0);
nd->rc=st.top();
st.pop();
nd->lc=st.top();
st.pop();
st.push(nd);
}
}
root=st.top();
st.pop();
}
bool cal(node *r){
if(r->op=='x') return r->val;
if(r->op=='!') return r->val=!cal(r->lc);
if(r->op=='&') return r->val=cal(r->lc) && cal(r->rc);
if(r->op=='|') return r->val=cal(r->lc) || cal(r->rc);
}
void go(node *r,bool f){
if(r->op=='x'){
table[r->no]=f?!root->val:root->val;
return;
}
if(r->op=='!'){
if(f) go(r->lc,1);
else go(r->lc,0);
}else if(r->op=='&'){
if(f){
if(r->rc->val==1) go(r->lc,1);
else go(r->lc,0);
if(r->lc->val==1) go(r->rc,1);
else go(r->rc,0);
}else{
go(r->lc,0);
go(r->rc,0);
}
}else if(r->op=='|'){
if(f){
if(r->rc->val==0) go(r->lc,1);
else go(r->lc,0);
if(r->lc->val==0) go(r->rc,1);
else go(r->rc,0);
}else{
go(r->lc,0);
go(r->rc,0);
}
}
return;
}
int main(){
//freopen("expr.in","r",stdin);
//freopen("expr.out","w",stdout);
getline(cin,s);
crtree();
cin>>n;
for(int i=1;i<=n;i++){
cin>>x;
leaf[i]->val=x;
}
cal(root);
go(root,1);
cin>>q;
for(int i=1;i<=q;i++){
cin>>qi;
cout<<table[qi]<<endl;
}
return 0;
}