우선순위 큐(Priority Queue)란?
특징
구현 방식
주요 연산
활용 분야
구현
#include<iostream>
#include <queue>
#include<vector>
using namespace std;
class priorityqueue
{
public:
void Push(int data)
{
heap.push_back(data);
PriUp(heap.size()-1);
}
int Pop()
{
int priority = heap[0];
heap[0] = heap[heap.size()-1];
heap.pop_back();
if(heap.empty() == false)
PriDown(0);
return priority;
}
int Peek()
{
if(heap.empty() == false)
return heap[0];
return 0;
}
bool IsEmpty()
{
return heap.empty();
}
private:
void PriUp(int index)
{
while(index > 0 && heap[(index-1)/2] < heap[index])
{
swap(heap[(index-1)/2], heap[index]);
index = (index-1)/2;
}
}
void PriDown(int index)
{
int maxIndex = index;
int left = index*2+1;
int right = index*2+2;
if(left < heap.size() && heap[left] > heap[maxIndex])
maxIndex = left;
if(right < heap.size() && heap[right] > heap[maxIndex])
maxIndex = right;
if(index != maxIndex)
{
swap(heap[index],heap[maxIndex]);
PriDown(maxIndex);
}
}
private:
vector<int> heap;
};
int main()
{
priorityqueue q;
q.Push(2);
q.Push(3);
q.Push(5);
q.Push(1);
q.Push(4);
int a{};
q.Pop();
q.Pop();
q.Pop();
q.Pop();
}