백준
백준 소스코드 [C++] 1918 후위 표기식
Hani_Levenshtein
2020. 8. 17. 07:33
https://www.acmicpc.net/problem/1918
1918번: 후위 표기식
첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 A~Z의 문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의 수식��
www.acmicpc.net
백준 소스코드 [C++] 1918 후위 표기식
#include <iostream>
#include <stack>
#include <string>
int change(char x) {
if (x == '+' || x == '-') return 1;
if (x == '*' || x == '/') return 2;
if (x == '(') return 0;
}
using namespace std;
int main() {
string xx;
getline(cin, xx);
stack<char> ss;
for (int i = 0;i < (int)xx.length();i++) {
if ('A' <= xx[i] && xx[i] <= 'Z') cout << xx[i];
else if (xx[i] <= '(') ss.push(xx[i]);
else if (xx[i] <= ')') {
while (ss.top() != '(') {
cout << ss.top();
ss.pop();
}
ss.pop();
}
else {
while (!ss.empty() && (change(ss.top()) >= change(xx[i]))) {
cout << ss.top();
ss.pop();
}
ss.push(xx[i]);
}
}
while (!ss.empty()) {
cout << ss.top();
ss.pop();
}
return 0;
}