[BOJ] 14888: 연산자 끼워넣기

이슬비·2023년 1월 20일
0

Algorithm

목록 보기
61/110
post-thumbnail

1시간은 고민한 것 같다 ...

1. 내 풀이

import sys
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))
operator = list(map(int, input().split()))
answer = []
count = 1
result = a[0]

def dfs(start, operator_list):
    oper = operator_list.copy()
    print(oper, operator_list)
    global result
    global count
    
    if count == len(a):
        print('종료')
        answer.append(result)
        result = 0
        return
    
    for i in range(start, len(a)-1):
        if operator_list[0]:
            result += a[i+1]
            count +=1
            oper[0] -=1
            print(oper, operator_list)
            dfs(i+1, oper)
        if operator_list[1]:
            result -= a[i+1]
            count +=1
            oper[1] -=1
            dfs(i+1, oper)
        if operator_list[2]:
            print(oper, operator_list)
            result *= a[i+1]
            count +=1
            oper[2] -=1
            print(oper, operator_list)
            dfs(i+1, oper)
        if operator_list[3]:
            result = result//a[i+1]
            count +=1
            oper[3] -=1
            dfs(i+1, oper)

dfs(0, operator)
print(max(answer))
print(min(answer))

나 왜 골드 5...? 실버 1 문제도 이렇게나 어려운데 ... 이건 제출도 못해봤다. 왜냐하면 내가 했을 때도 테스트 케이스들이 다 틀렸었으니까 ^^ ㅎㅎ,,,

2. 다른 풀이

import sys

input = sys.stdin.readline
N = int(input())
num = list(map(int, input().split()))
op = list(map(int, input().split()))  # +, -, *, //

maximum = -1e9
minimum = 1e9


def dfs(depth, total, plus, minus, multiply, divide):
    global maximum, minimum
    if depth == N:
        maximum = max(total, maximum)
        minimum = min(total, minimum)
        return

    if plus:
        dfs(depth + 1, total + num[depth], plus - 1, minus, multiply, divide)
    if minus:
        dfs(depth + 1, total - num[depth], plus, minus - 1, multiply, divide)
    if multiply:
        dfs(depth + 1, total * num[depth], plus, minus, multiply - 1, divide)
    if divide:
        dfs(depth + 1, int(total / num[depth]), plus, minus, multiply, divide - 1)


dfs(1, num[0], op[0], op[1], op[2], op[3])
print(maximum)
print(minimum)

참고는 아래의 블로그에서 했다.
https://velog.io/@kimdukbae/BOJ-14888-%EC%97%B0%EC%82%B0%EC%9E%90-%EB%81%BC%EC%9B%8C%EB%84%A3%EA%B8%B0-Python


말도 안 나올 정도로 쉽게 풀어서 반성했다 ... 여기서 배워야 할 점은

  • dfs 함수에 여러개를 쓰자: 굳이 depth를 global로 설정 안해도 됨
  • max 계산할 때 list를 넣는 것보다 maximum 값을 넣어서 비교하는 게 훨씬 빠르다.
  • 동시에 if 문이 필요할 때에는 elif가 아닌 if를 써야 한다.

3. 마치며

나는야 빈껍데기 골드다 ...

profile
정말 알아?

0개의 댓글