[Gold II] Title: 중앙값 구하기, Time: 88 ms, Memory: 39036 KB -BaekjoonHub

This commit is contained in:
SSUM
2025-05-05 17:16:31 +09:00
parent 77603a007a
commit 577ae8a33b
2 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
# [Gold II] 중앙값 구하기 - 2696
[문제 링크](https://www.acmicpc.net/problem/2696)
### 성능 요약
메모리: 39036 KB, 시간: 88 ms
### 분류
자료 구조, 우선순위 큐
### 제출 일자
2025년 5월 5일 17:16:23
### 문제 설명
<p>어떤 수열을 읽고, 홀수번째 수를 읽을 때 마다, 지금까지 입력받은 값의 중앙값을 출력하는 프로그램을 작성하시오.</p>
<p>예를 들어, 수열이 1, 5, 4, 3, 2 이면, 홀수번째 수는 1번째 수, 3번째 수, 5번째 수이고, 1번째 수를 읽었을 때 중앙값은 1, 3번째 수를 읽었을 때는 4, 5번째 수를 읽었을 때는 3이다.</p>
### 입력
<p>첫째 줄에 테스트 케이스의 개수 T(1 ≤ T ≤ 1,000)가 주어진다. 각 테스트 케이스의 첫째 줄에는 수열의 크기 M(1 ≤ M ≤ 9999, M은 홀수)이 주어지고, 그 다음 줄부터 이 수열의 원소가 차례대로 주어진다. 원소는 한 줄에 10개씩 나누어져있고, 32비트 부호있는 정수이다.</p>
### 출력
<p>각 테스트 케이스에 대해 첫째 줄에 출력하는 중앙값의 개수를 출력하고, 둘째 줄에는 홀수 번째 수를 읽을 때 마다 구한 중앙값을 차례대로 공백으로 구분하여 출력한다. 이때, 한 줄에 10개씩 출력해야 한다.</p>

View File

@@ -0,0 +1,37 @@
import sys
import queue
from heapq import heappush, heappop
input = sys.stdin.readline
T = int(input())
for _ in range(T):
M = int(input())
max_heap = []
min_heap = []
result = []
numbers = []
while len(numbers) < M:
numbers.extend(list(map(int, input().split())))
for i in range(M):
num = numbers[i]
if(len(max_heap)<=len(min_heap)):
heappush(max_heap,-num)
else:
heappush(min_heap, num)
if min_heap and -max_heap[0] > min_heap[0]:
temp_max = -heappop(max_heap)
temp_min = heappop(min_heap)
heappush(max_heap, -temp_min)
heappush(min_heap, temp_max)
if (i + 1) % 2 == 1:
result.append(-max_heap[0])
print(len(result))
for i in range(0, len(result), 10):
print(*result[i:i+10])