본문 바로가기
백준 삼성

[python] 14888 - 연산자 끼워넣기

by 다데기 2022. 8. 30.

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

 

14888번: 연산자 끼워넣기

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

www.acmicpc.net

 

정답률 49.466%

난이도 실1

 


코드 설명

1. 입력 받기

2. dfs 구현

3. 나눗셈 구현

 

 

※ 주의할 점

  • 나눗셈 구현시 음수, 양수 나눠서 구현
  • dfs구현시 주의사항들(아래 case에 영향받지 않게 인수에서 계산한다던지)
# 2. dfs 구현
def count(depth, res, plus, minus, multi, div):
    global min_ans, max_ans
    if depth == N:
        if res < min_ans:
            min_ans = res
        if res > max_ans:
            max_ans = res
        return

    if plus:
        count(depth + 1, res + numArray[depth], plus - 1, minus, multi, div)

    if minus:
        count(depth + 1, res - numArray[depth], plus, minus - 1, multi, div)

    if multi:
        count(depth + 1, res * numArray[depth], plus, minus, multi - 1, div)
        
	# 3. 나눗셈 구현
    if div:
        if res >= 0:
            count(depth + 1, res // numArray[depth], plus, minus, multi, div - 1)
        else:
            count(depth + 1, -(-res // numArray[depth]), plus, minus, multi, div - 1)

# 1. 입력 받기
min_ans = 1000000000
max_ans = -1000000000
N = int(input())
numArray = list(map(int, input().split()))
opArray = list(map(int, input().split()))
count(1, numArray[0], *opArray)
print(max_ans)
print(min_ans)

 


코드 결과