Files
python/TangDou/CSP-J/J2-2022/expr_4_QiuZhi_LuoJi_CopyFromNormal.cpp

61 lines
1.2 KiB
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
/*
0&(1|0)|(1|1|1&0)
答案:1
(0|1&0|1|1|(1|1))&(0&1&(1|0)|0|1|0)&0
答案:0
*/
unordered_map<char, int> h{{'|', 1}, {'&', 2}};
stack<int> num;
stack<char> stk;
void eval() {
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char p = stk.top();
stk.pop();
int r;
if (p == '|')
r = b | a;
else if (p == '&')
r = b & a;
num.push(r);
}
int main() {
string s;
cin >> s;
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
int x = 0;
while (i < s.size() && isdigit(s[i])) {
x = x * 10 + s[i] - '0';
i++;
}
i--;
num.push(x);
} else if (s[i] == '(')
stk.push(s[i]);
else if (s[i] == ')') {
while (stk.top() != '(') eval();
stk.pop();
} else {
while (stk.size() && h[stk.top()] >= h[s[i]]) eval();
stk.push(s[i]);
}
}
while (stk.size()) eval();
printf("%d\n", num.top());
return 0;
}