지구정복

[우선순위큐] 백준 - 가운데를 말해요 (1655) 본문

데이터 엔지니어링 정복/Algorithm

[우선순위큐] 백준 - 가운데를 말해요 (1655)

eeaarrtthh 2022. 6. 20. 21:42
728x90
반응형
SMALL

-문제

https://www.acmicpc.net/problem/1655

 

1655번: 가운데를 말해요

첫째 줄에는 백준이가 외치는 정수의 개수 N이 주어진다. N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. 그 다음 N줄에 걸쳐서 백준이가 외치는 정수가 차례대로 주어진다. 정수는 -1

www.acmicpc.net

 

 

-자바 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt( br.readLine() );
		
		//최대힙, 최소힙 우선순위큐를 만든다.
		PriorityQueue<Integer> minH = new PriorityQueue<>();
		PriorityQueue<Integer> maxH = new PriorityQueue<>(Collections.reverseOrder());
		
		//메모리 절약을 위해 스트링버퍼 사용
		StringBuffer sb = new StringBuffer();
		
		for( int i=0; i<N; i++ ) {
			int n = Integer.parseInt( br.readLine() );
			
			//최대힙과 최소힙의 size가 같다면 최대힙에 정수를 배정
			//같지 않으면 최소힙에 배정
			if( minH.size() == maxH.size() ) maxH.add(n);
			else minH.add(n);
			
			//minH 비워져있으면 F인데 !이므로 T && 최대힙peek가 최소힙 peek보다 크면 교체
			if( !minH.isEmpty() && maxH.peek() > minH.peek() ) {
				int tmp = maxH.poll();
				maxH.add( minH.poll() );
				minH.add( tmp );
			}
			
			sb.append( maxH.peek() + "\n" );
		}
		
		System.out.println( sb );
	}

}
728x90
반응형
LIST
Comments