우선순위 큐 : priority_queue (최대힙, 최소힙)
- 💾 알고리즘/알고리즘 기초
- 2020. 9. 15. 17:57
우선순위 큐(Priority Queue)
- 일반적인 큐는 제일 먼저 들어간 데이터가 가장 먼저 나오게 되는 자료구조이다.
- 이와 달리 우선순위 큐(Priority Queue)는 들어간 순서에 상관없이 일정한 규칙에 따라 우선순위를 선정하고, 우선순위가 가장 높은 데이터가 가장 먼저 나오게 된다.
최대힙
PriorityQueue의 생성자에 Collections.reverseOrder() 을 주어야 한다.
import java.util.*;
// 최대힙 (priority_queue : 우선순위 큐)
public class cp73 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PriorityQueue<Integer> queue =
new PriorityQueue<>(Collections.reverseOrder());
while(true){
int a = sc.nextInt();
if(a == -1) break;
if(a == 0){
if(queue.isEmpty()){
System.out.println("-1\n");
}else{
System.out.println("top = " + queue.poll());
}
}
else{
queue.add(a);
}
}
//return 0;
}
}
최소힙
최대힙과 동일하며 단지 PriorityQueue 생성자에 아무것도 주지 않으면 최소힙이 된다.
// 최소 힙 (priority_queue : 우선순위 큐)
public class cp74 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PriorityQueue<Integer> queue = new PriorityQueue<>();
while(true){
int a = sc.nextInt();
if(a == -1) break;
if(a == 0){
if(queue.isEmpty()){
System.out.println("-1\n");
}else{
System.out.println("top = " + queue.poll());
}
}
else{
queue.add(a);
}
}// end while
}
}
'💾 알고리즘 > 알고리즘 기초' 카테고리의 다른 글
우선순위 큐 : 객체의 특정값으로 정렬 (0) | 2020.09.25 |
---|---|
유니온 파인드 (Union-Find) (0) | 2020.09.23 |
[DP : 동적계획법] 최대연속부분수열 (0) | 2020.06.19 |
최대이익 - 동적계획법 (0) | 2020.06.19 |
최단경로 찾기 - 재귀/메모제이션/동적 프로그래밍 (0) | 2020.06.11 |