본문으로 바로가기

백준_14888

category 알고리즘 2021. 4. 25. 19:08

www.acmicpc.net/problem/14888

 

14888번: 연산자 끼워넣기

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 

www.acmicpc.net

다른 언어로 풀었다면 재귀를 이용한 조합으로 풀었을 테지만 python의 강력한 permutations함수를 이용해 풀었습니다. 연산자의 경우의 수 조합을 구하고, 그 조합대로 연산을 해준 후 max와 min 값과 비교해서 갱신해 주었습니다.

그리고 num이 -일때 나누기에 주의해야 합니다.

시간 효율은 좋지 않지만 그래도 통과하내요

 

import itertools

N = int(input())
array = list(map(int, input().split(' ')))
operate = list(map(int, input().split(' ')))

plus = operate[0] * ['+']
minus = operate[1] * ['-']
double = operate[2] * ['*']
half = operate[3] * ['/']

op_list = plus + minus + double + half
permutation = itertools.permutations(op_list, len(op_list))
op_list = list(set(permutation))


def operations(num, num1, oper):
    if oper == '+':
        return num + num1
    elif oper == '-':
        return num - num1
    elif oper == '*':
        return num * num1
    else:
        if num < 0:
            return -(-num // num1)
        else:
            return num // num1

max_num = -99999999
min_num = 99999999

for oper in op_list:
    result = array[0]

    for i in range(N - 1):
        result = operations(result, array[i + 1], oper[i])

    max_num = max(max_num, result)
    min_num = min(min_num, result)

print(max_num)
print(min_num)

'알고리즘' 카테고리의 다른 글

백준_1966  (0) 2021.05.09
백준_유레카이론  (0) 2021.05.05
백준_20055  (0) 2021.04.25
백준_12026  (0) 2021.04.11
프로그래머스_등굣길  (0) 2021.04.11