【解題】Zerojudge f377. 運算式轉換

題目連結

f377. 運算式轉換

我的想法

中序式轉後序式的基本題目,概念詳見:【筆記】前序式、中序式與後序式

參考解答

f377
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
#define ouo ios_base::sync_with_stdio(false), cin.tie(0)
#define ll long long
#define db double
using namespace std;

int order(char cr) {
if (cr == '+' || cr == '-')
return 1;
else if (cr == '*' || cr == '/')
return 2;
return 0;
}

int main() {
ouo;
string str;
while (getline(cin, str)) {
stack<char> symbol;
string ans = "";

for (int i = 0; i < str.length(); i++) {
if (str[i] == '(') {
symbol.push('(');
} else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
if (symbol.empty()) {
symbol.push(str[i]);
} else {
while (order(str[i]) <= order(symbol.top())) {
ans += symbol.top();
symbol.pop();
if (symbol.empty()) {
break;
}
}
symbol.push(str[i]);
}
} else if (str[i] == ')') {
while (symbol.top() != '(') {
ans.push_back(symbol.top());
symbol.pop();
}
symbol.pop();
} else if (isalpha(str[i])) {
ans.push_back(str[i]);
}
}
while (!symbol.empty()) {
ans.push_back(symbol.top());
symbol.pop();
}
for (int i = 0; i < ans.length(); i++) {
cout << ans[i] << " ";
}
cout << "\n";
}
return 0;
}