목차

중앙값 측정

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()