Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 트리
- 다이나믹프로그래밍
- 플로이드-워셜
- 구현
- GROUP BY
- 서브쿼리
- 그래프 탐색
- 분할정복
- join
- 우선순위큐
- 누적합
- MST
- 브루트포스
- BFS
- 재귀
- 그리디
- DP
- 다이나믹 프로그래밍
- 다시
- DFS
- 해시
- 수학
- 그래프 이론
- 투포인터
- 다익스트라
- 시뮬레이션
- 에라토스테네스의 체
- 자료구조
- 크루스칼
- 백트래킹
Archives
- Today
- Total
기록하고 까먹지 말기
14888 본문
날짜 : 2022. 12. 12
사용 언어 : python
문제
코드
import sys
from itertools import permutations
n = int(sys.stdin.readline()) # 수의 개수
num = list(map(int, sys.stdin.readline().split())) # 숫자 입력
temp = list(map(int, sys.stdin.readline().split())) # 덧셈, 뺄셈, 곱셈, 나눗셈
op = list()
for _ in range(temp[0]): op.append("+")
for _ in range(temp[1]): op.append("-")
for _ in range(temp[2]): op.append("*")
for _ in range(temp[3]): op.append("/")
max_value = -1e9
min_value = 1e9
def fun():
global max_value, min_value
for i in permutations(op, n-1): # 연산자들에 대한 모든 순열
t = num[0]
for j in range(1, n):
if i[j-1] == "+": t += num[j]
elif i[j-1] == "-": t -= num[j]
elif i[j-1] == "*": t *= num[j]
elif i[j-1] == "/": t = int(t / num[j])
max_value = max(max_value, t)
min_value = min(min_value, t)
fun()
print(max_value)
print(min_value)
백트래킹 활용 풀이(출처 아래 기입)
# 백트래킹 (Python3 통과, PyPy3도 통과)
import sys
input = sys.stdin.readline
N = int(input())
num = list(map(int, input().split()))
op = list(map(int, input().split())) # +, -, *, //
maximum = -1e9
minimum = 1e9
def dfs(depth, total, plus, minus, multiply, divide):
global maximum, minimum
if depth == N:
maximum = max(total, maximum)
minimum = min(total, minimum)
return
if plus:
dfs(depth + 1, total + num[depth], plus - 1, minus, multiply, divide)
if minus:
dfs(depth + 1, total - num[depth], plus, minus - 1, multiply, divide)
if multiply:
dfs(depth + 1, total * num[depth], plus, minus, multiply - 1, divide)
if divide:
dfs(depth + 1, int(total / num[depth]), plus, minus, multiply, divide - 1)
dfs(1, num[0], op[0], op[1], op[2], op[3])
print(maximum)
print(minimum)
풀이
순열풀이
- 각 연산에 대해서 +, -, *, / 를 개수에 따라 리스트에 저장한 후 permutation을 이용해 순열을 생성한다.
- 해당 순열에 따라서 연산자를 비교하고 그에따라 계산하면서 값을 생신한 후 아웃풋을 출력한다.
알게된 점
- 백트래킹 문제지만 다른 방식으로 풀 수 있었다.
참고 사이트
- DFS(모범답안) 참고: https://velog.io/@kimdukbae/BOJ-14888-연산자-끼워넣기-Python
[BOJ 14888] 연산자 끼워넣기 (Python)
링크위 문제를 보고 2가지 풀이 방법이 떠올랐다. 하나는 연산자들에 대한 순열을 구하여 푸는 방법이다. 다른 하나는 DFS를 이용해 최대, 최솟값을 구하는 방법이다. 순열은 파이썬 permutations 모
velog.io