https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14tDX6AFgCFAYD&categoryId=AV14tDX6AFgCFAYD&categoryType=CODE&problemTitle=%EA%B3%84%EC%82%B0%EA%B8%B0&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1
- 포스팅 이유
- 스택을 사용한 기본문제 중 가장 난이도 있는 문제라고 생각함
- 후위 표현식을 만드는 방식 과 계산하는 방식은 정확히 기억하고 있는 편이 도움이 될거라 생각함
1. 나의 풀이
import sys
sys.stdin = open("input.txt")
T = 10
icp = {
'+' : 1,
'*' : 2,
'-' : 1,
"/" : 2,
"(" : 3
}
isp = {
'+' : 1,
'*' : 2,
'-' : 1,
"/" : 2,
"(" : 0
}
def to_back(inp) :
N = len(inp)
result = [0] * N
stack =[]
j=0
for tmp in inp :
if tmp.isdigit() :
result[j] = tmp
j+=1
else:
if not stack :
stack.append(tmp)
continue
else :
if tmp == ')' :
while stack[-1] != '(' :
result[j] = stack.pop()
j+=1
stack.pop()
elif icp[tmp] > isp[stack[-1]] :
stack.append(tmp)
else :
while icp[tmp] <= isp[stack[-1]] :
result[j] = stack.pop()
j+=1
stack.append(tmp)
result = filter(lambda x : x != 0, result)
return result
def calc(back_equ) :
result = 0
stack = []
for tmp in back_equ :
if tmp.isdigit() :
stack.append(tmp)
else :
num2 = int(stack.pop())
num1 = int(stack.pop())
if tmp == "+" :
tmp_result = num1+num2
elif tmp == "*" :
tmp_result = num1*num2
elif tmp=="-" :
tmp_result = num1-num2
elif tmp=="/" :
tmp_result = num1 // num2
stack.append(tmp_result)
return stack[0]
for tc in range(1, T+1):
N= int(input())
inp = input()
back_equ = to_back(inp)
result = calc(back_equ)
print("#{} {}".format(tc, result))