solution
1. 순열(permutations) 이용해 연산자의 순서 리스트를 만듦
2. set()으로 중복 제거
# 14888, 연산자 끼워넣기
import sys
from itertools import permutations
N = int(sys.stdin.readline().rstrip())
num = list(map(int, sys.stdin.readline().split()))
arr = list(map(int, sys.stdin.readline().split()))
operator = []
for i in range(4):
for j in range(arr[i]):
operator.append(i)
op = list(permutations(operator))
max_ = -1000000000
min_ = 1000000000
for op_candidate in op:
ans = num[0]
for i in range(len(op_candidate)):
if op_candidate[i] == 0:
ans = ans + num[i+1]
elif op_candidate[i] == 1:
ans = ans - num[i+1]
elif op_candidate[i] == 2:
ans = ans * num[i+1]
else:
if ans < 0:
ans = (-1) * ans // num[i+1]
ans = (-1) * ans
else:
ans = ans // num[i+1]
max_ = max(ans, max_)
min_ = min(ans, min_)
print(max_)
print(min_)
시간 초과
2. set()으로 중복 제거
# 14888, 연산자 끼워넣기
import sys
from itertools import permutations
N = int(sys.stdin.readline().rstrip())
num = list(map(int, sys.stdin.readline().split()))
arr = list(map(int, sys.stdin.readline().split()))
operator = []
for i in range(4):
for j in range(arr[i]):
operator.append(i)
op = set(list(permutations(operator)))
max_ = -1000000000
min_ = 1000000000
for op_candidate in op:
ans = num[0]
for i in range(len(op_candidate)):
if op_candidate[i] == 0:
ans = ans + num[i+1]
elif op_candidate[i] == 1:
ans = ans - num[i+1]
elif op_candidate[i] == 2:
ans = ans * num[i+1]
else:
if ans < 0:
ans = (-1) * ans // num[i+1]
ans = (-1) * ans
else:
ans = ans // num[i+1]
max_ = max(ans, max_)
min_ = min(ans, min_)
print(max_)
print(min_)
528580KB
1428ms
문제 출처 https://www.acmicpc.net/problem/14888
'알고리즘 > 백트래킹' 카테고리의 다른 글
파이썬 | 백준 | 15650 | N과 M(2) | lst = range(1, n+1) (0) | 2020.08.27 |
---|