BOJ 1927 최소힙

less than 1 minute read

  1. 변수

    int N // 주어지는 test case 담을 변수
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    int chk // test case 돌면서 현재 받는 입력 변수
    
  2. 구현로직

    1. if(chk == 0) 우선순위 큐에서 가장 작은 값을 출력하고 그 값을 제거

    2. else면 queue에 add

  3. 코드

    package baekjoon.Silver;
       
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.PriorityQueue;
       
    public class BOJ_1927_최소힙 {
    	public static void main(String[] args) throws Exception {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		int N = Integer.parseInt(br.readLine());
    		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    		int chk = 0; // 현재 입력받는 수가 어떤 수인지 check
    		StringBuilder sb = new StringBuilder();
       
    		for (int tc = 0; tc < N; tc++) {
    			chk = Integer.parseInt(br.readLine());
    			if (chk == 0) {
    				if (pq.isEmpty())
    					sb.append(0).append('\n');
    				else {
    					sb.append(pq.poll()).append('\n');
    				}
    			} else {
    				pq.add(chk);
    			}
    		} // end of testCase
       
    		System.out.println(sb.toString());
       
    	} // end of main
    }
    
  4. 느낀점

    • pq가 비어있는 경우엔 0 을 출력해주는 것을 놓쳤다 (문제를 꼼꼼히 읽자!)

    • 우선순위큐를 poll 할때 앞에서 뽑는 지 뒤에서 뽑는지 헷갈렸다!

      => pq.poll()하면 맨앞에 제일 작은 수부터 뽑혀!

      참고) image

Leave a comment