priority queue : 각 데이터마다 우선순위(Priority)가 부여되어 있어, 들어온 순서에 상관없이 우선순위가 가장 높은 데이터가 가장 먼저 나가는 자료구조
자식 인덱스 / 2부모 인덱스 * 2(부모 인덱스 * 2) + 1#include <bits/stdc++.h>
using namespace std;
int heap[100005];
int sz = 0; // heap에 들어있는 원소의 수
void push(int x){
heap[++sz] = x;
int idx = sz;
while(idx != 1){
int par = idx/2;
if(heap[par] <= heap[idx]) break;
swap(heap[par], heap[idx]);
idx = par;
}
}
int top(){
return heap[1];
}
void pop(){
heap[1] = heap[sz--];
int idx = 1;
// 왼쪽 자식의 인덱스(=2*idx)가 size보다 크면 idx는 리프
while(2*idx <= sz){
int lc = 2*idx, rc = 2*idx+1; // 왼쪽 자식, 오른쪽 자식
int min_child = lc; // 두 자식 중 작은 인덱스를 담을 예정
if(rc <= sz && heap[rc] < heap[lc])
min_child = rc;
if(heap[idx] <= heap[min_child]) break;
swap(heap[idx],heap[min_child]);
idx = min_child;
}
}
int main(){
push(10); push(2); push(5); push(9); // {10, 2, 5, 9}
cout << top() << '\n'; // 2
pop(); // {10, 5, 9}
pop(); // {10, 9}
cout << top() << '\n'; // 9
push(5); push(15); // {10, 9, 5, 15}
cout << top() << '\n'; // 5
pop(); // {10, 9, 15}
cout << top() << '\n'; // 9
return 0;
}
priority_queuehttps://en.cppreference.com/cpp/container/priority_queue
#include <bits/stdc++.h>
using namespace std;
int main(void){
priority_queue<int> pq; // 최대 힙
// priority_queue<int, vector<int>, greater<int>>로 선언시 최소 힙
pq.push(10); pq.push(2); pq.push(5); pq.push(9); // {10, 2, 5, 9}
cout << pq.top() << '\n'; // 10
pq.pop(); // {2, 5, 9}
cout << pq.size() << '\n'; // 3
if(pq.empty()) cout << "PQ is empty\n";
else cout << "PQ is not empty\n";
pq.pop(); // {2, 5}
cout << pq.top() << '\n'; // 5
pq.push(5); pq.push(15); // {2, 5, 5, 15}
cout << pq.top() << '\n'; // 15
}
priority_queue<int, vector<int>, greater<int>>로 선언
단일 숫자면 greater 안 쓰고 그냥 값 넣고 뺄 때 -1 곱하면 최소힙처럼 쓸 수 있다는 사실