[백준] 14888번 연산자 끼워넣기 with python
2021. 5. 7. 14:22ㆍ코딩테스트 준비/백준
반응형
# 연산자 끼워넣기
import copy
n=int(input())
number=list(map(int,input().split()))
operation=list(map(int,input().split()))
oper_max,oper_min=-float('inf'),float('inf')
def dfs(operation,cnt,result):
global oper_max,oper_min
result_copy=result
if cnt==n-1:
oper_max=max(oper_max,result)
oper_min=min(oper_min,result)
return
for i in range(0,4):
oper_copy=copy.deepcopy(operation)
result=result_copy
if oper_copy[i]>0:
oper_copy[i]-=1
if i==0:
result=result+number[cnt+1]
elif i==1:
result=result-number[cnt+1]
elif i==2:
result=result*number[cnt+1]
else:
if result<0 and number[cnt+1]>0:
result=-result
result=-(result//number[cnt+1])
else:
result=(result//number[cnt+1])
dfs(oper_copy,cnt+1,result)
dfs(operation,0,number[0])
print(oper_max,oper_min)
dfs의 핵심을 잘 떠올리면 문제를 푸는 것은 어렵지 않다.
dfs에서 재귀함수를 이용하여 구현할 때, 기존 배열에 있는 것을 건드리면서 넘어가게 되면
재귀방법을 이용하여 함수가 호출되었을 때 다른 함수의 호출된 변수에 영향을 미치게 된다.
따라서 이를 무마하기 위하여 result값을 copy한 변수를 만들고 dfs를 통하여 함수를 호출하게 되면
result값을 다시 copy된 result값으로 초기화해주는 과정을 거쳤다.
operation 리스트도 마찬가지로 deepcopy를 통하여 초기화해주는 과정을 거쳤다.
반응형
'코딩테스트 준비 > 백준' 카테고리의 다른 글
[백준] 18405번 경쟁적 전염 with python (0) | 2021.06.13 |
---|---|
[백준] 15686번 치킨 배달 with python (0) | 2021.06.12 |
[백준] 12865번 평범한 배낭 with python (0) | 2021.05.03 |
[백준] 12026번 BOJ 거리 구하기 with python (0) | 2021.05.03 |
[백준] 13549번 (숨바꼭질3 with python) (0) | 2021.04.17 |