본문 바로가기
Algorithm/Greedy

[파이썬] 백준 1781 : 컵라면 (골드2)

by 베짱이28호 2023. 11. 30.

[파이썬] 백준 1781 : 컵라면 (골드2)

 

1781번: 컵라면

상욱 조교는 동호에게 N개의 문제를 주고서, 각각의 문제를 풀었을 때 컵라면을 몇 개 줄 것인지 제시 하였다. 하지만 동호의 찌를듯한 자신감에 소심한 상욱 조교는 각각의 문제에 대해 데드라

www.acmicpc.net


문제


풀이

0. 방향성 생각

  • 현재 최선의 선택(점수 많이주는거)이 항상 최적의 결과를 불러오지 않는다.
  • 데드라인을 고려하면서 컵라면을 선택해야함
  • 순차적으로 골랐을 경우, 저장한 자료구조에서 데드라인을 넘긴 경우를 모두 제거해줘야함 <<<<< 중요
  • 역순으로 접근하면 현재 시점 t에서는 데드라인이 지난 문제들은 저장한 자료구조에 없다.

1. 입력

from collections import defaultdict as dd
import heapq as hq
import sys
input = lambda : sys.stdin.readline().rstrip()

info = dd(list)
for _ in range(int(input())):
    dead,score = map(int,input().split())
    info[dead].append(score)
info = sorted(list(info.items()))
  • defaultdict로 데드라인 : 얻을 수 있는 점수 리스트로 매핑한다
  • info에 데드라인 순으로 정렬

2. 탐색

heap = []
answer,deadline = 0,info[-1][0]
for _ in range(deadline):
    
    if info and deadline <= info[-1][0]:
        _,score = info.pop()
        
        for s in score:
            hq.heappush(heap,-s)
            
    if heap:
        answer += hq.heappop(heap)
    deadline -=1
    
print(-answer)
  • deadline이 t초면 최대 t개의 문제를 풀 수 있음
  • 시작 시간은 현재 deadline
  • info가 비어있지 않고, 현재 시간이 데드라인보다 작은 경우 문제를 풀 수 있다.
  • 이 경우 score가 담긴 리스트를 뽑아서 힙에 모조리 넣는다. (최대힙이라서 -붙여야함)
  • 한 사이클마다 힙에서 최대점수를 가진 문제를 뽑는다. 이후 현재 시점을 줄인다.

 

 


전체코드

from collections import defaultdict as dd
import heapq as hq
import sys
input = lambda : sys.stdin.readline().rstrip()

info = dd(list)
for _ in range(int(input())):
    dead,score = map(int,input().split())
    info[dead].append(score)
info = sorted(list(info.items()))

heap = []
answer,deadline = 0,info[-1][0]
for _ in range(deadline):
    
    if info and deadline <= info[-1][0]:
        _,score = info.pop()
        
        for s in score:
            hq.heappush(heap,-s)
            
    if heap:
        answer += hq.heappop(heap)
    deadline -=1
    
print(-answer)

 

코멘트

.

댓글