Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

행복한 개구리

백준 22.01.30. 14888번 - 연산자 끼워넣기 본문

Algorithm/BaekJoon

백준 22.01.30. 14888번 - 연산자 끼워넣기

HappyFrog 2022. 1. 30. 16:29

N = int(input())

ops = []
nums = []
result = []
nums = list(map(int, input().split()))
ops = list(map(int, input().split()))
m = -1e9
n = 1e9


def DFS(num, depth, add, sub, mul, div):
    if depth == N:
        if num not in result:
            result.append(num)
            return

    if add > 0:
        DFS(num + nums[depth], depth + 1, add - 1, sub, mul, div)
    if sub > 0:
        DFS(num - nums[depth], depth + 1, add, sub - 1, mul, div)
    if mul > 0:
        DFS(num * nums[depth], depth + 1, add, sub, mul - 1, div)
    if div > 0:
        DFS(int(num / nums[depth]), depth + 1,
            add, sub, mul, div - 1)


DFS(nums[0], 1, ops[0], ops[1], ops[2], ops[3])
print(max(result))
print(min(result))
  • 재귀를 사용하는데, 가장먼저 덧셈/뺄셈/곱셈/나눗셈이 시작할지 결정하기위해서 elif가 아닌 if문을 네가지로 적어서 네갈래로 나눠 탐색합니다.
  • 모든 경우의 수를 검색하고 끝까지 검색했을 때 result리스트에 num이 없다면 추가해주고 있다면 return합니다.
  • 마지막으로 result리스트에 저장된 값 중에서 max와 min을 출력합니다.