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
- 그래프 이론
- DFS
- 다익스트라
- 트리
- 서브쿼리
- 누적합
- 크루스칼
- BFS
- DP
- MST
- 분할정복
- 시뮬레이션
- 재귀
- 백트래킹
- 에라토스테네스의 체
- 수학
- 자료구조
- 브루트포스
- 플로이드-워셜
- 투포인터
- 다이나믹 프로그래밍
- 그래프 탐색
- 다이나믹프로그래밍
- 구현
- 다시
- 해시
- 그리디
- join
- 우선순위큐
- GROUP BY
Archives
- Today
- Total
기록하고 까먹지 말기
1715 본문
날짜 : 2022. 09. 23
사용 언어 : python
문제
코드
틀린코드(알고리즘 자체가 틀림)
import sys
n = int(sys.stdin.readline())
card = list()
card.append(0)
if n == 0:
print(card[0])
else:
nums = list()
for i in range(n):
t = int(sys.stdin.readline())
nums.append(t)
nums.sort()
for i in range(len(nums)):
result = card[i]+nums[i]
card.append(result)
total = 0
for i in range(2, len(card)):
total += card[i]
print(total)
정답코드
import sys
from queue import PriorityQueue
n = int(sys.stdin.readline())
if n == 1: # 비교 필요 x
print(0)
else:
result = 0
deck = PriorityQueue() # 우선순위 큐 형태의 덱 목록
for i in range(n):
t = int(sys.stdin.readline()) # 카드 입력
deck.put(t) # 카드 목록에 넣음
while deck.qsize() > 1:
a = deck.get() # 가장 작은 수의 덱 추출
b = deck.get() # 두번째로 작은 수의 덱 추출
s = a + b # 결합
result += s
deck.put(s) # 해당 덱 넣음
print(result)
알게된 점
- 맨 처음 단순 점화식을 통해 문제를 풀어보려고 했지만 출력초과가 나왔다. 아마 출력값이 비정상적으로 커졌기 때문인 것 같다.
- 그래서 우선순위 큐를 검색했고 제거하는 경우 자동적으로 min 값을 pop한다는 것을 알았다.
- 문제는 의외로 간단하게 풀렸다.
참고 사이트
- 우선순위 큐 : https://johnyejin.tistory.com/72
[Python]우선순위큐(PriorityQueue) 라이브러리
우선순위큐(PriorityQueue) | 데이터를 추가하는 것은 어떤 순서로 해도 노상관 | 제거될 때는 가장 작은 값을 제거 Class Import from queue import PriorityQueue 우선순위큐 생성 qre = PriorityQueue() qre =..
johnyejin.tistory.com
-