【问题描述】
详见洛谷:https://www.luogu.com.cn/problem/P7073
【代码来源】
改编自 https://www.cnblogs.com/wk-love-zsy/p/13949843.html
调试过程中还发现,若将代码中的 char op[maxn]; 修改为 string op;,在本机调试能通过,但在洛谷中出现 “Segmentation Fault” 错误。
百思不解,只能暂时归结为在线程序调试网站中使用的C++编译器版本不兼容。待商榷。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1000010; //It might degenerate into a single branching tree
int n,m;
char str[maxn]; //string str;
char op[maxn]; //if use "string op;", cause wrong
int w[maxn];
int e[maxn],ne[maxn],h[maxn],idx;
int stk[maxn],p;
bool f[maxn]; //stk[]'s flag, can affect root
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int dfs1(int u) { //Compute the value of the intermediate node
if(u<=n) return w[u]; //leaf node is variable, such as x1 etc.
if(op[u]=='!') return w[u]=!dfs1(e[h[u]]); //e[h[u]] is the child node of u
else if(op[u]=='&') {
w[u]=1; //if w[u]=0, the & operations' result is not affected
for(int i=h[u]; ~i; i=ne[i]) //~i equivalent to i!=-1
w[u]&=dfs1(e[i]);
return w[u];
} else {
w[u]=0; //if w[u]=1, the | operations' result is not affected
for(int i=h[u]; ~i; i=ne[i]) //~i equivalent to i!=-1
w[u]|=dfs1(e[i]);
return w[u];
}
}
void dfs2(int u) { //Which nodes affect the value of the root node
f[u]=true; //The current node affects the value of the root node
if(u<=n) return; //Leaf nodes have no children, so don't worry about it
if(op[u]=='!') dfs2(e[h[u]]);
else {
int a=e[h[u]],b=e[ne[h[u]]]; //u's two son is e[h[u]] and e[ne[h[u]]]
if(op[u]=='&') {
if(w[a]) dfs2(b); //if w[a]=1, b can affect the tree's root value
if(w[b]) dfs2(a);
} else { // '|' operation
if(!w[a]) dfs2(b); //if w[a]=0, b can affect the tree's root value
if(!w[b]) dfs2(a);
}
}
}
int main() {
cin.getline(str,maxn); //getline(cin,str);
cin>>n;
for(int i=1; i<=n; i++) cin>>w[i];
memset(h,-1,sizeof(h)); //Initialize the array h[] to value -1
m=n; //m>=n,as the subscript of the operator array op[]
for(int i=0; str[i]; i++) { //i<strlen(str) ->TLE
if(str[i]=='x') {
int k=0;
i++;
while(str[i]>='0' && str[i]<='9') k=k*10+str[i]-'0',i++;
stk[++p]=k;
} else if(str[i]=='!') {
op[++m]=str[i];
add(m,stk[p--]); //add an edge from '!' to stack top
stk[++p]=m; //add a new node into stack
i++;
} else { //& or |
op[++m]=str[i];
add(m,stk[p--]);
add(m,stk[p--]);
stk[++p]=m;
i++;
}
}
int root=stk[p]; //from tree's top to bottom
int ans=dfs1(root);
dfs2(root);
int q;
cin>>q;
while(q--) {
int x;
cin>>x;
if(f[x]) cout<<!ans<<endl;
else cout<<ans<<endl;
}
return 0;
}
/*
in1:
x1 x2 & x3 |
3
1 0 1
3
1
2
3
out1:
1
1
0
in2:
x1 ! x2 x4 | x3 x5 ! & & ! &
5
0 1 0 1 1
3
1
3
5
out2:
0
1
1
*/
【参考文献】
https://www.cnblogs.com/wk-love-zsy/p/13949843.html
https://www.acwing.com/problem/content/solution/2771/1/
https://www.bilibili.com/video/av670505820/
https://zhuanlan.zhihu.com/p/318429567
https://blog.csdn.net/weixin_44751167/article/details/119519451