알고리즘/BOJ
[백준] 14888_연산자 끼워넣기
엉아_
2021. 12. 7. 00:13
728x90
📕 문제
https://www.acmicpc.net/problem/14888
14888번: 연산자 끼워넣기
첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수,
www.acmicpc.net
💡 풀이법
1. 연산자의 개수를 받아서 연산자의 개수만큼 연산자를 만들어서 연산자 리스트(opp)에 담아준다.
(0: 덧셈, 1: 뺼셈, 2: 곱셈, 3: 나눗셈)
2. 나올수 있는 순서의 경우의 수를 permutation으로 만들어준다.
(단, 중복이 나올수 있기 떄문에 set을 해준다.
예를 들어, 0,1,1,2,3 이면 1이 두개이지만 순열은 두 개의 1을 다르게 보기 때문에 (0,1,1,2,3),(0,1,1,2,3) 두개를 만든다. )
3. 경우의 수 set을 for문을 돌면서 경우의 수 마다 계산을 해서 결과를 비교해준다.
from itertools import permutations
N = int(input())
numbers = list(map(int, input().split()))
opp_cnt = list(map(int, input().split()))
opp = []
for i, cnt in enumerate(opp_cnt):
opp += [i] * cnt
max_result, min_result = float('-inf'), float('inf')
opp_case = set(permutations(opp, len(opp)))
for opp_list in opp_case:
result = numbers[0]
for i in range(N-1):
if opp_list[i] == 0:
result += numbers[i+1]
elif opp_list[i] == 1:
result -= numbers[i+1]
elif opp_list[i] == 2:
result *= numbers[i+1]
else:
if result < 0:
result = -(-result//numbers[i+1])
else:
result //= numbers[i+1]
max_result = max(max_result, result)
min_result = min(min_result, result)
print(max_result)
print(min_result)