ps:problems:boj:1572
중앙값
ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 1572 |
문제명 | 중앙값 |
레벨 | 플래티넘 5 |
분류 |
우선순위큐 |
시간복잡도 | O(nlogn) |
인풋사이즈 | n <= 250,000 |
사용한 언어 | Python |
제출기록 | 57448KB / 1096ms |
최고기록 | 788ms |
해결날짜 | 2021/05/10 |
풀이
코드
"""Solution code for "BOJ 1572. 중앙값".
- Problem link: https://www.acmicpc.net/problem/1572
- Solution link: http://www.teferi.net/ps/problems/boj/1572
"""
import sys
from teflib import priorityqueue
INF = float('inf')
def main():
N, K = [int(x) for x in sys.stdin.readline().split()]
nums = [int(sys.stdin.readline()) for _ in range(N)]
median = INF
median_sum = 0
min_heap = priorityqueue.UpdatableHeap()
max_heap = priorityqueue.UpdatableHeap()
for i, num in enumerate(nums):
if i >= K:
num_to_delete = nums[i - K]
if num_to_delete <= median:
max_heap.delete(-num_to_delete)
else:
min_heap.delete(num_to_delete)
if num <= median:
max_heap.push(-num)
while len(max_heap) > len(min_heap) + 1:
min_heap.push(-max_heap.pop())
else:
min_heap.push(num)
while len(max_heap) < len(min_heap):
max_heap.push(-min_heap.pop())
median = -max_heap.top()
if i >= K - 1:
median_sum += median
print(median_sum)
if __name__ == '__main__':
main()
- Dependency: teflib.priorityqueue.UpdatableHeap
ps/problems/boj/1572.txt · 마지막으로 수정됨: 2022/06/29 05:49 저자 teferi
토론