코테/백준

[백준/JAVA] 11279번: 최대 힙

imname1am 2023. 6. 13. 14:57
반응형

🔺 문제

 

11279번: 최대 힙

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

 

 

🔺 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;
import java.io.*;
 
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
 
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());   // 내림차순 정렬
 
        int N = Integer.parseInt(br.readLine());        
        while(N --> 0) {
            int x = Integer.parseInt(br.readLine());
            
            if(x == 0) {
                sb.append(pq.isEmpty() ? 0 : pq.poll()).append("\n");
            } else {
                pq.offer(x);
            }
        }
        
        System.out.println(sb);
    }
}
cs
✅ 해결 아이디어
✔ 우선순위 큐 (내림차순 정렬)

내림차순 정렬을 위해 Collection.reverseOrder() 를 이용했다.

 


💬 느낀 점

우선순위 큐 오름차순 내림차순 정렬은 이제 알겠고,

사용자 정의 정렬만 어떻게 해결하면 될 듯하다...

 

1회독 2회독 3회독 4회독 5회독
V        
반응형