[Java] 백준(Baekjoon) 11279. 최대 힙
2024. 1. 26. 10:10ㆍAlgorithm/자료구조
https://www.acmicpc.net/problem/11279
11279번: 최대 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static List<Integer> list= new ArrayList<>();
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int cnt= Integer.parseInt(br.readLine());
StringBuilder sb= new StringBuilder();
for(int i=0;i<cnt;i++) {
int num= Integer.parseInt(br.readLine());
if(num==0) {
if(list.isEmpty()) {
sb.append("0\n");
}else {
sb.append(list.get(list.size()-1)+"\n");
list.remove(list.size()-1);
}
}else {
int idx= 0;
if(!list.isEmpty()) {
idx= Math.abs(Collections.binarySearch(list, num)+1);
}
list.add(idx, num);
}
}
System.out.println(sb.toString());
}
}
"최소 힙" 문제에서, 꺼내는 수를 리스트의 맨 뒤 index= (list.size()-1)로 변경(max 값)
최대 힙(Max-Heap)
=> 우선순위 큐(Priority Queue)를 활용하면 더 쉽게 구현할 수 있다.
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 IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> que = new PriorityQueue<>(Collections.reverseOrder());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
int num = Integer.parseInt(br.readLine());
if (num == 0)
sb.append(que.size() == 0 ? 0 : que.poll()).append('\n');
else que.add(num);
}
System.out.println(sb.toString());
}
}
'Algorithm > 자료구조' 카테고리의 다른 글
[Java] 백준(Baekjoon) 1620. 나는야 포켓몬 마스터 이다솜 (2) | 2024.01.29 |
---|---|
[Java] 백준(Baekjoon) 10815. 숫자카드 (0) | 2024.01.26 |
[Java] 백준(Baekjoon) 1927. 최소 힙 (0) | 2024.01.25 |
[Java] 백준(Baekjoon) 1764. 듣보잡 (1) | 2024.01.25 |
[Java] 백준(Baekjoon) 1158. 요세푸스 문제 (0) | 2024.01.24 |