포스트

BOJ-14888 연산자 끼워넣기

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

문제 소개

수열과 연산자(+, -, *, //)의 개수가 주어졌을 때 연산자를 끼워넣어 계산한 결과 중 최대값과 최소값은 구하는 문제이다.

문제 풀이

먼저 itertools.permutationsset()연산을 통해 중복이 포함된 수열을 계산하는 함수를 선언한다.

그리고 lambda를 이용하여 딕셔너리를 선언하여 문자열 형태의 연산자로 접근하였을 때 연산을 할 수 있게끔 하였다.

각 연산자의 개수를 입력받은 후 그를 토대로 가용한 연산자들의 문자열로 나타낸다.

반복문을 통해 연산자를 끼워넣는 경우의 수마다 결과를 계산하여 리스트candappend()하게되며, 마지막으로 max()min()을 통해 만들 수 있는 최대값과 최소값을 구한다.

코드

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
31
32
33
34
import sys
from itertools import permutations
input = lambda: sys.stdin.readline().rstrip()

def perm(s):
    return set(permutations(s))

op = {
    '+' : lambda x, y : x + y,
    '-' : lambda x, y : x - y,
    '*' : lambda x, y : x * y,
    '/' : lambda x, y : x // y if x > 0 else -((-x) // y)
}

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

t = ""
t += b[0] * '+'
t += b[1] * '-'
t += b[2] * '*'
t += b[3] * '/'

cand = []
for i in perm(t):
    temp = a[0]
    for j in range(n - 1):
        temp = op[i[j]](temp, a[j + 1])
    cand.append(temp)

print(max(cand))
print(min(cand))

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

인기 태그