본문 바로가기

프로그래밍/알고리즘(자바)

백준 14888 파이썬(DFS, *args 사용 방법)

문제 : https://www.acmicpc.net/problem/14888

14888번: 연산자 끼워넣기

배운점 :

*args로 함수 정의할 때 뿐 아니라 호출할때 도 사용할 수 있다.
보통은 함수 정의할때 여러 리스트를 호출하는 용도로 종종 쓰인다고 알고 있었는데 신기하다.

풀이 :

n = int(input())
nums = list(map(int, input().split()))
operators = list(map(int, input().split()))

# 초기화
max_value = -10**9
min_value = 10**9


def dfs(depth, total, plus, minus, multiply, divide):
    global max_value, min_value
    if depth == n:
        if max_value < total :
            max_value = total
        if min_value > total :
            min_value = total
        return 
    if plus:
        dfs(depth+1, total + nums[depth], plus-1, minus, multiply, divide)
    if minus:
        dfs(depth+1, total - nums[depth], plus, minus-1, multiply, divide)        
    if multiply:
        dfs(depth+1, total * nums[depth], plus, minus, multiply-1, divide)        
    if divide:
        if total > 0 :
            dfs(depth+1, total // nums[depth], plus, minus, multiply, divide-1)        
        else:   
            dfs(depth+1, -(-total // nums[depth]), plus, minus, multiply, divide-1)        

dfs(1, nums[0], *operators)

print(max_value)
print(min_value)