[PS] BOJ 1417 / 국회의원 선거

[PS] BOJ 1417 / 국회의원 선거
문제 링크: https://www.acmicpc.net/problem/1417
Thumbnail: Photo by Arnaud Jaegers (Unsplash)

풀이

먼저, 각 후보자를 투표 수를 기준으로 맵에 저장합니다.

이후, 투표 수를 기준으로 우선 순위 큐에 추가해주고, 다솜이보다 더 많은 표가 예상되는 후보들의 표를 1씩 줄여가며 계산합니다.

전체 코드

from heapq import heappush, heappop
input = open(0).readline

N = int(input())
count = {}
dasom = int(input())
needed = 0

for _ in range(N - 1):
    candidate = int(input())
    try:
        count[candidate] += 1
    except KeyError:
        count[candidate] = 1

queue = []
for vote in count:
    heappush(queue, (-vote, vote))
while queue:
    _, vote = heappop(queue)
    candidates = count[vote]
    while dasom <= vote and candidates > 0:
        dasom += 1
        needed += 1
        candidates -= 1
        count[vote] -= 1
        try:
            count[vote - 1] += 1
        except KeyError:
            count[vote - 1] = 1
        heappush(queue, (1 - vote, vote - 1))
    if dasom > vote:
        break
print(needed)

solution.py