-
Notifications
You must be signed in to change notification settings - Fork 0
/
1918.cpp
49 lines (43 loc) · 1.03 KB
/
1918.cpp
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
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
int main() {
stack<char> st;
unordered_map<char, int> prec;
prec.insert({'(', 0});
prec.insert({'+', 1});
prec.insert({'-', 1});
prec.insert({'*', 2});
prec.insert({'/', 2});
char ch;
while (cin >> ch) {
if (ch == '(')
st.push(ch);
else if (ch == ')') {
while (st.top() != '(') {
cout << st.top();
st.pop();
}
st.pop(); // ignore '('
} else if ('A' <= ch && ch <= 'Z') {
cout << ch;
} else { // ch is a operator
while (!st.empty()) {
char op = st.top();
if (prec[ch] <= prec[op]) {
cout << op;
st.pop();
} else {
break;
}
}
st.push(ch);
}
}
while (!st.empty()) {
cout << st.top();
st.pop();
}
return 0;
}