难道有人看题解不点赞的吗?
原题链接:P8815 [CSP-J 2022] 逻辑表达式
又是表达式求值`(>﹏<)′
我最弱的方面
特此,写篇题解纪念一下[]( ̄▽ ̄)*
前置芝士:表达式树
题目解析
- 我们先将原序列转换为表达式树的形式:
void calc() {
ll b=num.top();
num.pop();
ll a=num.top();
num.pop();
ch[++idx]=op.top();
op.pop();
e[idx][0]=a,e[idx][1]=b;
num.push(idx);
}
for(ll c:s) {
if(c=='(') op.push(c);
else if(c==')') {
while(op.top()!='(') calc();
op.pop();
} else if(isdigit(c)) {
ch[++idx]=c;
num.push(idx);
} else {
while(!op.empty() && op.top()!='(' && mp[op.top()]>=mp[c]) calc();
op.push(c);
}
}
while(!op.empty()) calc();其中:
数组用来存储编号为 的点的字符(1/0/&/|)
存储每个节点的儿子
存储符号
存储编号
存储 & 和 | 的优先级
- 接着,我们遍历这棵表达式树, 的返回值是以当前节点 为根的子树的值,而形如
a&b和a|b的“短路”的出现次数分别用 和 存储。
可以发现:
若 为数字,直接返回这个数字;
若 为&且 的左儿子的值为 ,则出现了“短路”;
若 为|且 的左儿子的值为 ,则出现了“短路”;
代码只需分类讨论即可:
ll dfs(ll u) {
if(isdigit(ch[u])) return ch[u]-'0';
if(ch[u]=='&') {
if(!dfs(e[u][0])) {
cnt1++;
return 0;
}
return dfs(e[u][1]);
}
if(dfs(e[u][0])) {
cnt2++;
return 1;
}
return dfs(e[u][1]);
}呼,该讲的都讲完了,下面是——
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll S=1e6+10,mod=10007;
map<char,ll> mp= {{'|',1},{'&',2}};
stack<ll> num;
stack<char> op;
ll e[S][2];
string s;
char ch[S];
ll n,idx,cnt1,cnt2;
void calc() {
ll b=num.top();
num.pop();
ll a=num.top();
num.pop();
ch[++idx]=op.top();
op.pop();
e[idx][0]=a,e[idx][1]=b;
num.push(idx);
}
ll dfs(ll u) {
if(isdigit(ch[u])) return ch[u]-'0';
if(ch[u]=='&') {
if(!dfs(e[u][0])) {
cnt1++;
return 0;
}
return dfs(e[u][1]);
}
if(dfs(e[u][0])) {
cnt2++;
return 1;
}
return dfs(e[u][1]);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>s;
for(char c:s) {
if(c=='(') op.push(c);
else if(c==')') {
while(op.top()!='(') calc();
op.pop();
} else if(isdigit(c)) {
ch[++idx]=c;
num.push(idx);
} else {
while(!op.empty() && op.top()!='(' && mp[op.top()]>=mp[c]) calc();
op.push(c);
}
}
while(!op.empty()) calc();
cout<<dfs(idx)<<"\n";
cout<<cnt1<<" "<<cnt2;
return 0;
}