2023.01.04 : 11296 절댓값 힙

‍박예서·2023년 1월 4일

코딩테스트

목록 보기
14/27

1. 문제

2. 아이디어

  • 우선순위 큐(힙)을 이용하는 문제이다.

3. 코드

import java.util.*;
import java.io.*;

class Main {  
  public static void main(String args[]) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringBuffer sb = new StringBuffer();

    int N = Integer.parseInt(br.readLine());

    // 최대 힙 정의
    PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
      
      @Override
      public int compare(Integer a, Integer b){
        if (Math.abs(a) != Math.abs(b)){
          return Math.abs(a) - Math.abs(b);
        }else{
          return a - b;
        }
      }
      
    }); // 최대 힙 정의 end

    int tmp_num;
    
    for(int i = 0 ; i < N;i++){
      tmp_num = Integer.parseInt(br.readLine());
      if (tmp_num != 0){
        pq.offer(tmp_num);
      }else{
        if(pq.size() == 0){
          sb.append("0");
        }
        else{
         sb.append(pq.poll());
        }
        sb.append("\n");
      }
    } // for end

    System.out.println(sb);
    
  } 
}

4. 느낀점 및 배운점

  • 우선순위 큐 (힙)

// 우선순위 큐 정의
PriorityQueue<타입명> pq = new PriorityQueue<>(new Comparator<Integer>(){
  
  @Override
  public int compare(타입명 a, 타입명 b){
  
    return 조건;
    // a가 b보다 작을 떄 음수가 반환된다면 a가 b보다 우선순위가 높다.

    }
  
  });
// 우선순위 큐에 삽입
pq.offer();
// 우선순위 큐에서 pop
pq.poll();
  • StringBuffer 로 쉽게 문자열의 처리가 가능하다.

0개의 댓글