반응형

https://www.acmicpc.net/problem/1918

 

1918번: 후위 표기식

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

www.acmicpc.net

 

스택을 이용하여 중위 표기식을 후위 표기식으로 변환시켜주었습니다.

 
 
#include <cstdio>
char stk[30], ch;
int top = -1;
int getPriority(char op) {
	if (op == '*' || op == '/') return 2;
	else if (op == '+' || op == '-') return 1;
	else return 0;
}
int main() {
	while ((ch = getchar()) != '\n') {
		if ('A' <= ch && ch <= 'Z') printf("%c", ch);
		else {
			if (ch == ')') {
				while (stk[top] != '(') printf("%c", stk[top--]);
				top--;
			}
			else if (ch == '(') stk[++top] = ch;
			else {
				while (top != -1 && getPriority(stk[top]) >= getPriority(ch))
					printf("%c", stk[top--]);
				stk[++top] = ch;
			}
		}
	}
	while (top != -1) printf("%c", stk[top--]);
}
반응형

'Algorithm' 카테고리의 다른 글

백준 2075 : N번째 큰 수  (0) 2021.11.15
백준 17298 : 오큰수  (0) 2021.11.15
백준 12899 : 데이터 구조  (0) 2021.11.15
백준 11505 : 구간 곱 구하기  (0) 2021.11.15
백준 2357 : 최솟값과 최댓값  (0) 2021.11.15

+ Recent posts