Skip to content

Commit 0b50271

Browse files
committed
[Gold II] Title: 중앙값 구하기, Time: 180 ms, Memory: 16356 KB -BaekjoonHub
1 parent 6b350d7 commit 0b50271

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Gold II] 중앙값 구하기 - 2696
2+
3+
[문제 링크](https://www.acmicpc.net/problem/2696)
4+
5+
### 성능 요약
6+
7+
메모리: 16356 KB, 시간: 180 ms
8+
9+
### 분류
10+
11+
자료 구조, 우선순위 큐
12+
13+
### 제출 일자
14+
15+
2025년 12월 5일 21:26:20
16+
17+
### 문제 설명
18+
19+
<p>어떤 수열을 읽고, 홀수번째 수를 읽을 때 마다, 지금까지 입력받은 값의 중앙값을 출력하는 프로그램을 작성하시오.</p>
20+
21+
<p>예를 들어, 수열이 1, 5, 4, 3, 2 이면, 홀수번째 수는 1번째 수, 3번째 수, 5번째 수이고, 1번째 수를 읽었을 때 중앙값은 1, 3번째 수를 읽었을 때는 4, 5번째 수를 읽었을 때는 3이다.</p>
22+
23+
### 입력
24+
25+
<p>첫째 줄에 테스트 케이스의 개수 T(1 ≤ T ≤ 1,000)가 주어진다. 각 테스트 케이스의 첫째 줄에는 수열의 크기 M(1 ≤ M ≤ 9999, M은 홀수)이 주어지고, 그 다음 줄부터 이 수열의 원소가 차례대로 주어진다. 원소는 한 줄에 10개씩 나누어져있고, 32비트 부호있는 정수이다.</p>
26+
27+
### 출력
28+
29+
<p>각 테스트 케이스에 대해 첫째 줄에 출력하는 중앙값의 개수를 출력하고, 둘째 줄에는 홀수 번째 수를 읽을 때 마다 구한 중앙값을 차례대로 공백으로 구분하여 출력한다. 이때, 한 줄에 10개씩 출력해야 한다.</p>
30+
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
public static void main(String[] args) throws IOException {
7+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
9+
int t = Integer.parseInt(br.readLine());
10+
11+
StringBuilder sb = new StringBuilder();
12+
for(int test=0; test<t; test++) {
13+
int m = Integer.parseInt(br.readLine());
14+
StringTokenizer st = null;
15+
16+
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> -Integer.compare(o1, o2));
17+
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
18+
19+
List<Integer> list = new ArrayList<>();
20+
for(int i=0; i<m; i++) {
21+
if(i%10 == 0) st = new StringTokenizer(br.readLine());
22+
23+
int num = Integer.parseInt(st.nextToken());
24+
25+
if(maxHeap.size() == minHeap.size()) minHeap.offer(num);
26+
else if(maxHeap.size() < minHeap.size()) maxHeap.offer(num);
27+
28+
while(maxHeap.size() > 0 && maxHeap.peek() > minHeap.peek()) {
29+
int temp = maxHeap.poll();
30+
maxHeap.offer(minHeap.poll());
31+
minHeap.offer(temp);
32+
}
33+
34+
if(i%2 == 0) list.add(minHeap.peek());
35+
}
36+
37+
sb.append(list.size());
38+
for(int i=0; i<list.size(); i++) {
39+
if(i%10 == 0) sb.append("\n");
40+
else sb.append(" ");
41+
sb.append(list.get(i));
42+
}
43+
sb.append("\n");
44+
}
45+
46+
System.out.println(sb.toString().trim());
47+
}
48+
49+
50+
}

0 commit comments

Comments
 (0)