ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 9426 |
문제명 | 중앙값 측정 |
레벨 | 플래티넘 5 |
분류 |
우선순위큐 |
시간복잡도 | O(nlogn) |
인풋사이즈 | n <= 250,000 |
사용한 언어 | Python |
제출기록 | 57444KB / 1056ms |
최고기록 | 792ms |
해결날짜 | 2021/05/07 |
"""Solution code for "BOJ 9426. 중앙값 측정".
- Problem link: https://www.acmicpc.net/problem/9426
- Solution link: http://www.teferi.net/ps/problems/boj/9426
"""
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 max_heap.size() > min_heap.size() + 1:
min_heap.push(-max_heap.pop())
else:
min_heap.push(num)
while max_heap.size() < min_heap.size():
max_heap.push(-min_heap.pop())
median = -max_heap.top()
if i >= K - 1:
median_sum += median
print(median_sum)
if __name__ == '__main__':
main()