[Algorithm][Python] 백준(BOJ) 14888 연산자 끼워넣기

최대 1 분 소요

[문제]

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

image image


풀이 : DFS

[내 코드]

import sys

n = int(input())
int_array= []
oper_count= []
result_min = 1e9
result_max = -1e9

int_array = list(map(int, sys.stdin.readline().split()))
oper_count = list(map(int, sys.stdin.readline().split()))

def dfs(depth, total ,plus, sub, mul, div):
    global result_min, result_max
    if depth == n:
        result_min = min(total, result_min)
        result_max = max(total, result_max)
        return

    if plus:
        dfs(depth+1, total+int_array[depth], plus-1, sub,mul,div)
    if sub:
        dfs(depth+1, total-int_array[depth],plus, sub-1,mul,div)
    if mul:
        dfs(depth+1, total*int_array[depth], plus,sub,mul-1,div)
    if div:
        dfs(depth+1, int(total/int_array[depth]),plus,sub,mul,div-1)

dfs(1, int_array[0],oper_count[0],oper_count[1],oper_count[2],oper_count[3])
print(result_max)
print(result_min)

image

💡주의
처음에 나눗셈 연산에서 a//b 로 했는데 정답이 틀렸다.
찾아보니

a // b : 몫
a / b : 소수점까지 계산
int(a/b) : 소수점 버림 </br>

정의만 봤을 때는 같은 의미인 것 같은데 음수의 경우 값이 다르게 나온다.

image

출처

그래서 a//b 로 쓰고 싶다면 양수일때와 음수일때를 따로 나눠서 사용해야한다.

if total>0: a//b
else : (-1)*(abs(a)//b)

댓글남기기