AcWing 4730. 逻辑表达式
作者:
jy9
,
2024-07-27 12:06:41
,
所有人可见
,
阅读 3
#include <iostream>
#include <unordered_map>
#include <stack>
using namespace std;
struct node{
int val, ands, ors;
};
stack<node> num;
stack<char> op;
unordered_map<char, int> mp = {{'(', 0}, {'|', 1}, {'&', 2}};
void eval(){
node b = num.top();
int b_ands = b.ands;
int b_ors = b.ors;
num.pop();
node a = num.top();
int a_ands = a.ands;
int a_ors = a.ors;
num.pop();
char x = op.top();
op.pop();
int ans = 0;
int ands = 0;
int ors = 0;
if(x == '&'){
ans = a.val&b.val;
if (!a.val){
ands = a_ands + 1;
ors = a_ors; //继承左子树ors
}
else{//全继承
ands = a_ands + b_ands;
ors = a_ors + b_ors;
}
}else if(x == '|'){
ans = a.val|b.val;
if(a.val){
ors = a_ors + 1;
ands = a_ands; //继承左子树ands,在这里ands写成ans了,废了我20分钟
}
else { //全继承
ors = a_ors + b_ors;
ands = a_ands + b_ands;
}
}
num.push({ans, ands, ors});
}
int main(){
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ ){
char t = str[i];
if(isdigit(t)) num.push({t-'0', 0, 0});
else if(t == '(') op.push('(');
else if(t == ')'){
while (op.top() != '(') eval();
op.pop();
}else{
while(op.size() && mp[t] <= mp[op.top()]) eval();
op.push(t);
}
}
while(op.size()) eval();
cout << num.top().val;
cout << endl;
cout << num.top().ands << ' ' << num.top().ors;
return 0;
}
细节决定成败,也决定了20分钟的用处....