文章目录
#include <iostream>
using namespace std;
class PriorityQueue
{
public:
int MAXIMUM();
int EXTRACT_MAX();
void INCREASE_KEY(int i, int key);
bool INSERT(int key);
PriorityQueue(int max_size)
{
this->max_size = max_size;
this->A = new int[max_size];
}
~PriorityQueue()
{
delete[] this->A;
this->A = NULL;
}
private:
int heap_size = 0;
int max_size = -1;
int *A = NULL;
int INF = 0x3F3F3F3F;
int LEFT(int i);
int RIGHT(int i);
int PARENT(int i);
void MAX_HEAPIFY(int A[], int i);
};
int PriorityQueue::LEFT(int i)
{
return 2 * i + 1;
}
int PriorityQueue::RIGHT(int i)
{
return 2 * (i + 1);
}
int PriorityQueue::PARENT(int i)
{
return (int)((i + 1) / 2) - 1;
}
void PriorityQueue::MAX_HEAPIFY(int A[], int i)
{
int l = this->LEFT(i);
int r = this->RIGHT(i);
int largest = i;
if (l < this->heap_size && A[l] > A[i])
{
largest = l;
}
if (r < this->heap_size && A[r] > A[largest])
{
largest = r;
}
if (largest != i)
{
swap(A[i], A[largest]);
MAX_HEAPIFY(A, largest);
}
}
int PriorityQueue::MAXIMUM()
{
return A[0];
}
int PriorityQueue::EXTRACT_MAX()
{
if (this->heap_size < 1)
{
return -1;
}
int max = A[0];
A[0] = A[this->heap_size - 1];
this->heap_size--;
this->MAX_HEAPIFY(A, 0);
return max;
}
void PriorityQueue::INCREASE_KEY(int i, int key)
{
A[i] = key;
while (i > 0 && A[this->PARENT(i) < A[i]])
{
swap(A[i], A[this->PARENT(i)]);
i = this->PARENT(i);
}
}
bool PriorityQueue::INSERT(int key)
{
if (this->heap_size < this->max_size)
{
this->heap_size++;
}
else
{
return false;
}
this->INCREASE_KEY(this->heap_size - 1, key);
return true;
}
int main()
{
PriorityQueue priorityQueue(10);
priorityQueue.INSERT(1);
cout << priorityQueue.MAXIMUM() << endl;
priorityQueue.INSERT(3);
cout << priorityQueue.MAXIMUM() << endl;
priorityQueue.INCREASE_KEY(1, 4);
cout << priorityQueue.EXTRACT_MAX() << endl;
cout << priorityQueue.EXTRACT_MAX() << endl;
cout << priorityQueue.EXTRACT_MAX() << endl;
return 0;
}