practivceAlgorithm/백준
[백준][Python] 14888 연산자 끼워넣기
findTheValue
2021. 7. 25. 14:57
경우의 수를 만들어 연산자를 대입하는 문제였다.
보자마자 DFS가 생각나서 설계했는데 처음에는 +-보다 */연산을 먼저 처리하는 줄 알고
문자열로 calculate를 쌓고 eval answer에 삽입햇으나 테케 통과 못하고 문제 다시일어보니
앞에서부터 순차 연산... str에서 int로 바꾸고 진입시마다 계산해주면서 들어갔다.
import sys
input = sys.stdin.readline
def DFS(idx,calculate):
if idx==N:
answer.append(calculate)
return
num = seqs[idx]
for operator in '+-*/':
if operator == '+'and opers[0]:
opers[0] -=1
DFS(idx+1,calculate+num)
opers[0] +=1
elif operator == '-' and opers[1]:
opers[1] -=1
DFS(idx+1,calculate-num)
opers[1] +=1
elif operator == '*' and opers[2]:
opers[2] -=1
DFS(idx+1,calculate*num)
opers[2] +=1
elif operator == '/' and opers[3]:
if calculate <0:
opers[3] -=1
DFS(idx+1,-((-calculate)//num))
opers[3] +=1
else:
opers[3] -=1
DFS(idx+1,calculate//num)
opers[3] +=1
N = int(input())
seqs = list(map(int,input().split()))
opers = list(map(int,input().split()))
answer=[]
DFS(1,seqs[0])
print(max(answer))
print(min(answer))