문제
https://www.acmicpc.net/problem/16637
접근 방법
- 중첩되는 괄호가 없으므로, 각 연산자마다 괄호 가질수 있는 경우의 수를 구하기 위해 비트 마스킹 사용
- 비트마스킹을 통해 괄호가 연속되는 경우의 수 백트래킹
- 스택을 통해 수식이 저장된 리스트의 결과 구하기
- 수식 계산시에 우선순위 없이 왼쪽 먼저 계산하는 조건을 지켜야 됨
풀이 코드
def cul(a,center,b):
if center == '+':
return a + b
elif center == '-':
return a - b
elif center == '*':
return a * b
def cal(string):
stack = []
for ch in string:
if ch.isdecimal():
if stack and not stack[-1].isdecimal() and stack[-1] != '(':
center = stack.pop()
a = stack.pop()
stack.append(cul(a,center,int(ch)))
else:
stack.append(int(ch))
elif ch == ')':
a = stack.pop()
stack.pop()
stack.append(a)
if len(stack) > 2:
b = stack.pop()
c = stack.pop()
a = stack.pop()
stack.append(cul(a,c,b))
else:
stack.append(ch)
if len(stack) > 2:
b = stack.pop()
c = stack.pop()
a = stack.pop()
stack.append(cul(a,c,b))
return stack[0]
N = int(input())
M = N // 2
text = list(input())
mx = cal(text)
for i in range(1<<M):
for j in range(M-1):
if i & (1<<j) and i & (1<<(j+1)):
break
else:
temp = text[:]
for j in range(M-1,-1,-1):
if i & (1<<j):
temp[j*2:j*2+3] = ['('] + text[j*2:j*2+3] + [')']
else:
pass
if mx < cal(temp):
mx = cal(temp)
print(mx)