2696번: 중앙값 구하기
첫째 줄에 테스트 케이스의 개수 T(1 ≤ T ≤ 1,000)가 주어진다. 각 테스트 케이스의 첫째 줄에는 수열의 크기 M(1 ≤ M ≤ 9999, M은 홀수)이 주어지고, 그 다음 줄부터 이 수열의 원소가 차례대로 주
www.acmicpc.net
import java.io.*;
import java.util.*;
public class Main {
static PriorityQueue<Integer> max_heap;
static PriorityQueue<Integer> min_heap;
static int median;
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int t_c=1;t_c<=T;t_c++) {
int M=sc.nextInt();
min_heap=new PriorityQueue<>();
max_heap=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
});
int n;
System.out.println(M/2+1);
median=sc.nextInt();
System.out.print(median+" ");
for(int i=2;i<=M;i++) {
n=sc.nextInt();
if(median>n) max_heap.add(n);
else if(median<n) min_heap.add(n);
else max_heap.add(n);
if(i%2!=0) {
while(max_heap.size()!=min_heap.size()) getMedian();
System.out.print(median+" ");
//System.out.println("median "+ median);
}
}
System.out.println();
}
}
static void getMedian() {
int temp;
if(max_heap.size()<min_heap.size()) {
temp=min_heap.poll();
max_heap.add(median);
median=temp;
}
else if(max_heap.size()>min_heap.size()) {
temp=max_heap.poll();
min_heap.add(median);
median=temp;
}
}
}
'코테 공부' 카테고리의 다른 글
[우선순위큐]절댓값 힙(백준 11286번, 자바) (0) | 2023.01.26 |
---|---|
[우선순위큐/힙] 최대 힙(백준 11279번, 자바) (0) | 2023.01.26 |
파이프 옮기기(백준 17070번, 자바) (0) | 2023.01.15 |
[DFS]주사위 굴리기2(23288번, 자바) (0) | 2023.01.12 |
[SWEX] 최적의 경로(1247번, 자바) (0) | 2023.01.03 |