알고리즘/백준

[백준/Python] 1715번 카드 정렬하기

ㅈㅣ니 2023. 9. 20.
반응형

드디어 골드문제 도전!

https://www.acmicpc.net/problem/1715

 

1715번: 카드 정렬하기

정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장

www.acmicpc.net

풀이

from queue import PriorityQueue

n = int(input())
card = PriorityQueue()
lst = []
for _ in range(n):
    card.put(int(input()))

for i in range(n-1):
    temp = card.get(card)+card.get(card)
    card.put(temp)
    lst.append(temp)
print(sum(lst))

처음에는 이렇게 풀었다. 우선순위 큐로 풀었는데 시간이 너무 오래 걸려서 heapq로 재도전!

from heapq import *

n = int(input())
card = []
lst = []
for _ in range(n):
    heappush(card,int(input()))
for i in range(n-1):
    temp = heappop(card)+heappop(card)
    heappush(card,temp)
    lst.append(temp)
print(sum(lst))

리스트를 힙 형태로 만들지 않고 pop하려하면 제대로 pop이 이루어지지 않는다는 걸 이번에 배웠다...ㅠㅠ

만약 heappush(card, int(input()) 을 안쓰고

card.append(int(input())) 으로 데이터를 입력받으면

heapify() 를 써서 heap형태로 만들어서 정렬해줘야한다는 걸 알게 되는 문제였음.

 

하... 그런데 시간이 단축되지 않는다... 나중에 좀 더 연구해봐야할듯..ㅠㅜ

반응형