[백준][Python] 14888. 연산자 끼워넣기
Silver Ⅰ 🔗14888. 연산자 끼워넣기
📝문제 요약
N개의 수로 이루어진 수열 A1, A2, …, AN이 주어진다. 또, 수와 수 사이에 끼워넣을 수 있는 N-1개의 연산자가 주어진다. 연산자는 덧셈(+), 뺄셈(-), 곱셈(×), 나눗셈(÷)으로만 이루어져 있다.
우리는 수와 수 사이에 연산자를 하나씩 넣어서, 수식을 하나 만들 수 있다. 이때, 주어진 수의 순서를 바꾸면 안 된다.
예를 들어, 6개의 수로 이루어진 수열이 1, 2, 3, 4, 5, 6이고, 주어진 연산자가 덧셈(+) 2개, 뺄셈(-) 1개, 곱셈(×) 1개, 나눗셈(÷) 1개인 경우에는 총 60가지의 식을 만들 수 있다. 예를 들어, 아래와 같은 식을 만들 수 있다.
- 1+2+3-4×5÷6
- 1÷2+3+4-5×6
- 1+2÷3×4-5+6
- 1÷2×3-4+5+6
식의 계산은 연산자 우선 순위를 무시하고 앞에서부터 진행해야 한다. 또, 나눗셈은 정수 나눗셈으로 몫만 취한다. 음수를 양수로 나눌 때는 C++14의 기준을 따른다. 즉, 양수로 바꾼 뒤 몫을 취하고, 그 몫을 음수로 바꾼 것과 같다. 이에 따라서, 위의 식 4개의 결과를 계산해보면 아래와 같다.
- 1+2+3-4×5÷6 = 1
- 1÷2+3+4-5×6 = 12
- 1+2÷3×4-5+6 = 5
- 1÷2×3-4+5+6 = 7
N개의 수와 N-1개의 연산자가 주어졌을 때, 만들 수 있는 식의 결과가 최대인 것과 최소인 것을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, …, AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 곱셈(×)의 개수, 나눗셈(÷)의 개수이다.
출력
첫째 줄에 만들 수 있는 식의 결과의 최댓값을, 둘째 줄에는 최솟값을 출력한다. 연산자를 어떻게 끼워넣어도 항상 -10억보다 크거나 같고, 10억보다 작거나 같은 결과가 나오는 입력만 주어진다. 또한, 앞에서부터 계산했을 때, 중간에 계산되는 식의 결과도 항상 -10억보다 크거나 같고, 10억보다 작거나 같다.
✏️문제 풀이
- 입력
n
: 숫자의 개수numbers
: 사용할 숫자들 (순서 고정)operators
: 연산자 개수 리스트 →[+, -, *, /]
- DFS 함수 정의
dfs(depth, total, +, -, *, /)
depth
: 몇 번째 숫자까지 계산했는지total
: 지금까지 계산한 결과연산자 개수
: 현재 남은 연산자 개수
- 재귀를 멈추는 조건
depth == n
: 모든 숫자를 다 사용한 경우- 지금까지의
total
값을최댓값
,최솟값
으로 비교해서 갱신
- 백트래킹 - 각 연산자 사용
+
가 남아 있으면total + numbers[depth]
계산하고,+1
감소시키고 재귀 호출-
,*
,/
도 똑같이 계산하여 모든 조합을 다 탐색
- 초기값 세팅 & DFS 호출
min_result = float('inf')
,max_result = float('-inf')
로 설정(무한대)- 처음 숫자부터 시작해서
dfs(1, numbers[0], ...)
호출
- 결과 출력 : 최댓값 먼저, 그다음 최솟값 출력
코드와 함께 보는 풀이
# 입력: 수의 개수
n = int(input())
# 숫자 리스트 입력
numbers = list(map(int, input().split()))
# 연산자 개수 입력: +, -, *, // 순서
operators = list(map(int, input().split())) # [+, -, *, /]의 개수
# DFS 탐색 함수 정의
def dfs(depth, total, plus, minus, multiply, divide):
global min_result, max_result
# 모든 숫자를 다 썼을 때
if depth == n:
# 최댓값, 최솟값 갱신
min_result = min(min_result, total)
max_result = max(max_result, total)
return
# 연산자 개수가 남아있는 경우 각각 재귀 호출
if plus > 0:
dfs(depth + 1, total + numbers[depth], plus - 1, minus, multiply, divide)
if minus > 0:
dfs(depth + 1, total - numbers[depth], plus, minus - 1, multiply, divide)
if multiply > 0:
dfs(depth + 1, total * numbers[depth], plus, minus, multiply - 1, divide)
if divide > 0:
# 나눗셈은 정수 나눗셈
dfs(depth + 1, int(total / numbers[depth]), plus, minus, multiply, divide - 1)
# 최솟값, 최댓값 초기화 (무한대 / -무한대)
min_result = float('inf')
max_result = float('-inf')
# DFS 시작: 첫 번째 숫자(numbers[0])부터 시작
dfs(1, numbers[0], operators[0], operators[1], operators[2], operators[3])
# 결과 출력
print(max_result)
print(min_result)
💯제출 코드
n = int(input())
numbers = list(map(int, input().split()))
operators = list(map(int, input().split()))
def dfs(depth, total, plus, minus, multiply, divide):
global min_result, max_result
if depth == n:
min_result = min(min_result, total)
max_result = max(max_result, total)
return
if plus > 0:
dfs(depth + 1, total + numbers[depth], plus - 1, minus, multiply, divide)
if minus > 0:
dfs(depth + 1, total - numbers[depth], plus, minus - 1, multiply, divide)
if multiply > 0:
dfs(depth + 1, total * numbers[depth], plus, minus, multiply - 1, divide)
if divide > 0:
dfs(depth + 1, int(total / numbers[depth]), plus, minus, multiply, divide - 1)
min_result = float('inf')
max_result = float('-inf')
dfs(1, numbers[0], operators[0], operators[1], operators[2], operators[3])
print(max_result)
print(min_result)
댓글남기기