Files
python/TangDou/CSP-J/J2-2022/expr_2_InFixToPostFix_LuoJi_CopyFromNormal.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

59 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
/*
中缀的逻辑表达式 转 后缀的逻辑表达式
测试用例1:
0&(0|1|0)
答案:
001|0|&
测试用例2:
1|0&1&(0|1|0)|(0&1)
答案:
101&01|0|&|01&|
*/
unordered_map<char, int> h{{'|', 1}, {'&', 2}};
string s;
string t;
stack<char> stk;
int main() {
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--;
t.append(to_string(x));
} else if (isalpha(s[i]))
t.push_back(s[i]);
else if (s[i] == '(')
stk.push(s[i]);
else if (s[i] == ')') {
while (stk.top() != '(') {
t.push_back(stk.top());
stk.pop();
}
stk.pop();
} else {
while (stk.size() && h[s[i]] <= h[stk.top()]) {
t.push_back(stk.top());
stk.pop();
}
stk.push(s[i]);
}
}
while (stk.size()) {
t.push_back(stk.top());
stk.pop();
}
// printf("%s", t.c_str());
cout << t << endl;
return 0;
}