[백준] 14888번 - 연산자 끼워넣기

yerimstar·2022년 1월 20일
0

BFS/DFS

목록 보기
2/4

문제

14888번

아이디어

순열을 활용하여 간단하게 풀 수 있는 문제였다.
DFS 파트 문제였기 때문에 DFS 코드는 구글링을 통해 학습했다.

소스코드

1) 순열

# 연산자 끼워넣기
import sys
from itertools import permutations

N = int(sys.stdin.readline())
number = list(map(int,sys.stdin.readline().split()))
operator = list(map(int,sys.stdin.readline().split()))

min_value = 1e9
max_value = -1e9

check = 0
operators = []
for o in operator:
    check += 1
    if o != 0:
        for _ in range(o):
            if check == 1:
                operators.append("+")
            elif check == 2:
                operators.append("-")
            elif check == 3:
                operators.append("*")
            elif check == 4:
                operators.append("/")

ops = list(set(permutations(operators,N-1)))

for op in ops:
    result = number[0]
    for i in range(N-1):
        if op[i] == '+':
            result += number[i+1]
        elif op[i] == '-':
            result -= number[i+1]
        elif op[i] == '*':
            result *= number[i+1]
        elif op[i] == '/':
            result = int(result/number[i+1])

    max_value = max(result,max_value)
    min_value = min(result,min_value)

print(max_value)
print(min_value)

2) DFS
DFS 코드 참고

profile
백엔드 개발자

1개의 댓글

comment-user-thumbnail
2022년 1월 20일

파이썬에서 순열을 만드는 게 있었다니.... 잘 알아갑니다

답글 달기