본문 바로가기
코딩테스트/Python

[python 백준 2696] 중앙값 구하기

by nahkim 2023. 4. 9.

📜 접근 방법

❌ 실패 코드

✅ 정답 코드

import sys
import heapq
import math

t = int(sys.stdin.readline())

for i in range(t):
    arr = []
    n = int(sys.stdin.readline())
    if n > 10:
        k = math.ceil(n / 10)
        for i in range(k):
            arr += list(map(int, sys.stdin.readline().split()))
    else:
        arr = list(map(int, sys.stdin.readline().split()))
    m = arr[0]
    big = 0
    small = 0
    big_heap = []
    small_heap = []
    res = []
    for j in range(n):
        if j % 2 == 0:
            if j == 0:
                res.append(m)
            else:
                if m < arr[j]:
                    big += 1
                    heapq.heappush(big_heap, arr[j])
                else:
                    small += 1
                    heapq.heappush(small_heap, -arr[j])

                if big == 2:
                    # 최소힙
                    heapq.heappush(small_heap, -m)
                    m = heapq.heappop(big_heap)
                elif small == 2:
                    # 최대힙
                    heapq.heappush(big_heap, m)
                    m = -heapq.heappop(small_heap)
                big = 0
                small = 0
                res.append(m)
        else:
            if m < arr[j]:
                big += 1
                heapq.heappush(big_heap, arr[j])
            else:
                small += 1
                heapq.heappush(small_heap, -arr[j])
    
    print(len(res))
    for i in range(len(res)):
        if i != 0 and i % 9 == 0:
            print(res[i])
        else:
            print(res[i], end=" ")
    print()

💡알게 된점

혹시나 33%에서 틀렸다고 뜬다면 출력하는 곳에 문제가 있었으니 그 부분을 다시 한번 잘 볼것!
뭐가 잘못된지 한참 찾았다...