728x90
14888번: 연산자 끼워넣기
첫째 줄에 수의 개수 N2≤N≤11가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. 1≤Ai≤100 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈+의 개수, 뺄셈−의 개수,
www.acmicpc.net
문제 설명
- 순서가 있는 N개의 숫자를 받고 그 숫자 사이에 N-1개의 연산자를 삽입하는 문제
- 중복을 허용하고, 4종류의 연산자로 이루어진 N-1 길이의 순열을 모두 탐색하는 방법으로 접근
고민 한 부분
- DFS 방식으로 탐색을 하며 이미 탐색한 순열은 다시 탐색하지 않도록 가지치기할 방법 line39
더보기
N-1 x 4 크기의 visited 배열을 활용해 depth 번째에 삽입 될 연산자가 이미 사용됐다면 탐색하지 않는 방식으로 탐색 영역을 줄임
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, math, copy | |
## 조합 문제 > backtracking | |
min = math.inf | |
max = -math.inf | |
def calx,y,op: | |
if op == 0: | |
r = x+y | |
elif op == 1: | |
r = x - y | |
elif op == 2: | |
r = x * y | |
else : | |
r = absx // y | |
if x <0: | |
r = -r | |
return r | |
def DFSperm,depth=0: | |
global max, min | |
## 탈출조건 | |
if sumnumoperators == 0: | |
result = numbers[0] | |
for i in rangeN−1: | |
result = calresult,numbers[i+1],perm[i] | |
if result > max: | |
max = result | |
if result < min: | |
min = result | |
return | |
for i in range4: | |
# visit | |
## visited -> 해당 depth에 같은 operator가 사용됐으면 가지치기 | |
if num_operators[i] >0 and visited[depth][i] == 0: | |
num_operators[i] -= 1 | |
visited[depth][i] =1 | |
perm.appendi | |
# next node | |
DFSperm,depth+1 | |
# undo visit | |
num_operators[i] += 1 | |
visited[depth][i] = 0 | |
perm.pop | |
if __name__ == "__main__": | |
turn_in = 0 | |
if turn_in == 0: | |
sys.stdio = open′testcase.txt′ | |
N = intsys.stdio.readline() | |
numbers = listmap(int,sys.stdio.readline(.split)) | |
num_operators = listmap(int,sys.stdio.readline(.split)) | |
# + - x / | |
else: | |
N = intsys.stdin.readline() | |
numbers = listmap(int,sys.stdin.readline(.split)) | |
num_operators = listmap(int,sys.stdin.readline(.split)) | |
visited = [[0] * 4 for i in rangeN] | |
perm = [] # 연산자 순서대로 받는 임시 | |
DFSperm | |
printmax | |
printmin |
Lesson learned
max_ = max(max_, result)
min_ = min(min_, result)
- 최대, 최소값을 갱신할 때, python의 내장 함수 max, min을 사용해 코드 길이와 실수를 줄일 수 있음 line29 32
from itertools import permutations
test_list = [1,2,3,4,5] # 순열을 만들 대상들
L = 3 # 만들 순열의 길이
perm_generator = permutations(test_list, L)
- python에 itertools 모듈에 permutations를 활용하면 list item으로 구성된 N 크기의 순열을 모두 생성하는 generator를 만들 수 있음. 이렇게 풀게되면 시간초과로 통과를 하지 못하지만 간단하기 때문에 먼저 시도해볼만 한 것 같음
- perm_generator를 for문에 사용하거나 next 함수를 사용해 요소를 하나씩 반환할 수도 있음
'알고리즘 공부 > 백준 문제풀이' 카테고리의 다른 글
[백준 python] 14501번 퇴사 0 | 2022.08.05 |
---|---|
[백준 python] 14889번 스타트와 링크 0 | 2022.08.05 |
[백준 python] 14891번 톱니바퀴 0 | 2022.08.05 |
[백준 python] 14502번 연구소 0 | 2022.08.02 |
[백준 python] 14503번 로봇 청소기 0 | 2022.08.02 |