사용자 도구

사이트 도구


ps:problems:boj:2696

중앙값 구하기

ps
링크acmicpc.net/…
출처BOJ
문제 번호2696
문제명중앙값 구하기
레벨골드 2
분류

우선순위큐

시간복잡도O(T * nlogn)
인풋사이즈T<=1000, n<=9999
사용한 언어Python
제출기록31100KB / 88ms
최고기록68ms
해결날짜2021/05/10
태그

[라이] 우선순위 큐

풀이

코드

"""Solution code for "BOJ 2696. 중앙값 구하기".

- Problem link: https://www.acmicpc.net/problem/2696
- Solution link: http://www.teferi.net/ps/problems/boj/2696
"""

import heapq
import sys

INF = float('inf')


def main():
    T = int(sys.stdin.readline())
    for i in range(T):
        M = int(sys.stdin.readline())
        print(M // 2 + 1)
        max_heap = []
        min_heap = []
        median = INF
        read_count = 0
        while read_count < M:
            nums = [int(x) for x in sys.stdin.readline().split()]
            for num in nums:
                if num < median:
                    heapq.heappush(max_heap, -num)
                    if len(max_heap) > len(min_heap) + 1:
                        heapq.heappush(min_heap, -heapq.heappop(max_heap))
                else:
                    heapq.heappush(min_heap, num)
                    if len(max_heap) < len(min_heap):
                        heapq.heappush(max_heap, -heapq.heappop(min_heap))
                median = -max_heap[0]
                read_count += 1
                if read_count % 2:
                    print(median, end=('\n' if read_count % 20 == 19 else ' '))
        print()


if __name__ == '__main__':
    main()

토론

댓글을 입력하세요:
T Q H​ R D
 
ps/problems/boj/2696.txt · 마지막으로 수정됨: 2022/07/05 16:16 저자 teferi