코딩테스트/BOJ

[백준][순열] 15659. 연산자 끼워넣기(3)

박소민 2023. 11. 5. 21:43
15659. 연산자 끼워넣기(3)
 

15659번: 연산자 끼워넣기 (3)

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

www.acmicpc.net

 

📍 파이썬에서 permutaion 사용시 꼭 for 문 안에서 사용하기!!
      - 가끔 perm 사용하면 메모리 터질 때가 있었는데, 이건 perm()한 것을 한 번에 다른 곳에 담아서 그럼
       파이썬의 경우 for문 한번 돌때마다 GC가 비우기 때문에 for문 안에서 하나씩 불러서 사용하면 메모리 터지지 않음!!!

 

 

  • 다른 사람 풀이
    • ex)연산자 개수가 1 1 2 1 인경우 -> operator= ['+', '-', '*', '*', '//']
    • 위처럼 만들어진 연산자로 조합을 만들면 중복된게 발생하므로 set()해서 하나씩 불러주기
      • 숫자,연산자 하나씩 불러서 조합 후 계산
    • eval: 문자열로 작성된 계산식을 숫자로 계산해줌
from itertools import permutations

N = int(input())

numbers = list(map(int, input().split()))

plus, minus, multi, divide = map(int, input().split())

operator = []

operator.extend(['+'] * plus)
operator.extend(['-'] * minus)
operator.extend(['*'] * multi)
operator.extend(['//'] * divide)

min_val = int(1e9)
max_val = -int(1e9)

for op_set in set(permutations(operator)):
    expression = []
    for i in range(len(numbers)):
        expression.append(str(numbers[i]))
        if i < len(op_set):
            expression.append(op_set[i])

    expression = ''.join(expression)
    min_val = min(min_val, eval(expression))
    max_val = max(max_val, eval(expression))

print(max_val)
print(min_val)