티스토리 뷰

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

 

15903번: 카드 합체 놀이

첫 번째 줄에 카드의 개수를 나타내는 수 n(2 ≤ n ≤ 1,000)과 카드 합체를 몇 번 하는지를 나타내는 수 m(0 ≤ m ≤ 15×n)이 주어진다. 두 번째 줄에 맨 처음 카드의 상태를 나타내는 n개의 자연수 a1,

www.acmicpc.net

 

 

👩‍💻문제 이해

합이 최소가 되도록 해야하기 떄문에 heappop 두 번으로 가장 작은 숫자를 가진 card 두장을 뽑은 후,

두 장을 더한 값을 다시 heappush로 넣어주면 된다.

 

 

 

👩‍💻heappop, heappush, heapify를 사용한 코드 : 성공🌈

# 15903번 : 카드 합체 놀이

from heapq import heappop, heappush, heapify
n, m = map(int, input().split())

cards = [int(i) for i in input().split()]

# cards 리스트를 heap으로 변환
heapify(cards)


for i in range(m):
    card1 = heappop(cards)
    card2 = heappop(cards)
    
    heappush(cards, card1+card2)
    heappush(cards, card2+card1)
    
print(sum(cards))

 

 

 

Point

1. list안에 정수값 한줄로 받기
[int(i) for i in input().split()]

2. list -> heap 전환
heapify(list)
댓글
최근에 올라온 글
«   2024/09   »
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
Total
Today
Yesterday