아이공의 AI 공부 도전기

[Baekjoon] 14888번 : 연산자 끼워넣기 (Python, 백트래킹)

 

     

 

 

 

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

 

14888번: 연산자 끼워넣기

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

www.acmicpc.net

코드 링크

https://github.com/stellaluminary/Baekjoon

 

GitHub - stellaluminary/Baekjoon

Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.

github.com

 

Python

 

방법 1 - 메모리 30840KB / 시간 136ms / 코드 길이 754B

 

본 문제는 연산자를 활용한 백트래킹 문제이다.

둘째 줄에 입력으로 받는 N개의 정수에 대하여 사이사이 연산자를 사용하고 그 가짓수 중 최대값과 최소값을 구하는 문제로 연산자에 대한 백트래킹을 고려하면 된다.

 

처음에는 잘못생각하여 각 숫자에 대한 for문도 넣었지만 추후 그것은 잘못되었다는 것을 깨닫고 연산자에 대한 for문만을 활용하도록 수정하였다.

 

추가로 유의해야하는 것은 %에 대한 몫을 구할 때 주의해야한다는 것과 백트래킹이 일어나는 상황에서의 연산자 숫자 제거이다.

 

import sys
input = sys.stdin.readline

def dfs(idx):
    if sum(o) == 0:
        sv.append(t[-1])
        return

    for j in range(4):
        if o[j] == 0:
            continue

        if j == 0:
            t.append(t[-1] + a[idx])
        elif j == 1:
            t.append(t[-1] - a[idx])
        elif j == 2:
            t.append(t[-1] * a[idx])
        elif j == 3:
            if t[-1] < 0:
                tmp = -(abs(t[-1]) // a[idx])
            else:
                tmp = t[-1] // a[idx]
            t.append(tmp)
        o[j] -= 1
        dfs(idx+1)
        t.pop()
        o[j] += 1

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

t = [a[0]]

sv = []
dfs(1)

sv.sort()
print(sv[-1])
print(sv[0])

 

방법 2 - 메모리 30840KB / 시간 136ms / 코드 길이 765B

 

방법 1과 비슷하지만 약간 다른 방법을 활용한 방법

 

import sys
input = sys.stdin.readline

def dfs(idx):
    global ans, maxR, minR
    if idx == n:
        maxR = max(maxR, ans)
        minR = min(minR, ans)
        return

    for i in range(4):
        tmp = ans
        if o[i] == 0:
            continue

        if i == 0:
            ans += a[idx]
        elif i == 1:
            ans -= a[idx]
        elif i == 2:
            ans *= a[idx]
        elif i == 3:
            if ans < 0:
                ans = -(abs(ans) // a[idx])
            else:
                ans //= a[idx]
        o[i] -= 1
        dfs(idx+1)
        ans = tmp
        o[i] += 1

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

ans = a[0]
maxR = -(1e9)
minR = 1e9
dfs(1)
print(maxR)
print(minR)

 

방법 3 - itertools.permutations

 

itertools.permutations를 활용하여 각 숫자에 따른 연산자를 순열로 개수를 처리하여 각 연산자마다 넣는 방향을 고려할 수도 있다.

 

 

 

 

 

0000 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading