danbibibi
article thumbnail

1. 문제

문제 바로가기> BOJ 1918번: 후위 표기식

 

1918번: 후위 표기식

첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 알파벳 대문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의

www.acmicpc.net

 

2. 풀이

<cpp />
#include<iostream> #include<string> #include<stack> #define MAX 32001 using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); string expr; cin >> expr; stack<char> st; // 우선 순위가 낮은 연산자 (+, -) 부터 큰 연산자 (*, /) 순으로 쌓임 // 연산자 우선 순위 : () > *, / > +, - for (int i = 0; i < expr.size(); i++) { if (expr[i] == '+' || expr[i] == '-') { while (!st.empty() && st.top()!='(') { cout << st.top(); st.pop(); } st.push(expr[i]); } else if (expr[i] == '*' || expr[i] == '/') { while (!st.empty() && (st.top() == '*' || st.top() == '/')) { cout << st.top(); st.pop(); } st.push(expr[i]); } else if (expr[i] == '(') st.push(expr[i]); else if (expr[i] == ')') { while (st.top() != '(') { cout << st.top(); st.pop(); } st.pop(); // '(' pop } else cout << expr[i]; // 알파벳 대문자 } while (!st.empty()) { // 남은 연산자 출력 cout << st.top(); st.pop(); } }

'문제 풀이 > 백준' 카테고리의 다른 글

BOJ 2636번: 치즈  (0) 2023.03.18
BOJ 2842번 : 집배원 한상덕  (0) 2023.03.10
BOJ 21758번: 꿀 따기  (0) 2023.02.25
BOJ16946번: 벽 부수고 이동하기 4  (0) 2023.02.25
BOJ 17471번: 게리맨더링  (0) 2023.02.23
profile

danbibibi

@danbibibi

꿈을 꾸는 시간은 멈춰 있는 것이 아냐 두려워하지 마 멈추지 마 푸른 꿈속으로