1.优先级队列:是一种用来维护一组元素构成的集合S的数据结构,这一组元素中的每一个都有一个关键字key
对优先队列执行的操作有1) 查找;2) 插入一个新元素;3) 删除. 4)返回最大或最小值
Insert(S,x):把元素x插入到集合S。
MaxMum(S):返回S中的具有最大关键字的元素
ExtractMaxMum(S):删除并返回S中的具有最大关键字的元素
IncreaseKey(S,i,Key):将第i个元素的关键字的值增加到k,这里k值不能小于i原来关键字的值。
最大优先级队列不管各元素的入队顺序,在出队时,总是对应优先级最大的元素出队。
最大优先级队列一般用二叉树来实现。因为考虑到,对于最大优先级队列来讲,我们关心的只是最大值,因此,这时的二叉树只需要具备下面这个性质,那么就可以实现了:
性质A:总是让二叉树中的每一个节点的key(也就是优先级)值比该节点的子节点的key值大。
#include <iostream>
using namespace std;
const int INF = 999999;
/
// 以下代码在堆排序中已讲解过 ///
void MaxHeapify(int *a, int i, int len)
{
int lt = 2*i, rt = 2*i+1;
int largest;
if(lt <= len && a[lt] > a[i])
largest = lt;
else
largest = i;
if(rt <= len && a[rt] > a[largest])
largest = rt;
if(largest != i)
{
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
MaxHeapify(a, largest, len);
}
}
void BuildMaxHeap(int *a, int size)
{
for(int i=size/2; i>=1; --i)
MaxHeapify(a, i, size);
}
void PrintArray(int data[], int size)
{
for (int i=1; i<=size; ++i)
cout <<data[i]<<" ";
cout<< endl << endl;
}
// 返回具有最大关键字的元素
int HeapMaximum(int *a)
{
return a[1];
}
// 去掉并返回具有最大关键字的元素
// 注意:这里每次MaxHeapify的是heapsize
int HeapExtractMax(int *a, int &heapsize)
{
if(heapsize < 1)
cout << "Heap Underflow" << endl;
int max = a[1];
a[1] = a[heapsize];
--heapsize;
MaxHeapify(a, 1, heapsize);
return max;
}
// 将元素a[i]的值增加到key
void HeapIncreaseKey(int *a, int i, int key)
{
if(key < a[i])
cout << "New key is smaller than current key" << endl;
a[i] = key;
while(i > 1 &&a[i/2] < a[i])
{
int temp = a[i];
a[i] = a[i/2];
a[i/2] = temp;
i /= 2;
}
}
// 插入关键字为key的元素
void MaxHeapInsert(int *a, int key, int &heapsize)
{
++heapsize;
a[heapsize] = -INF;
HeapIncreaseKey(a, heapsize, key);
}
int main()
{
int len, heapsize;
int arr[100] = {0, 15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1};
// 区别len 和 heapsize
// heapsize是堆的大小,而len是初始数组的总大小。
len = heapsize = 12;
// 首先建堆
BuildMaxHeap(arr, len);
cout << "建堆后: " << endl;
PrintArray(arr, len);
// 使用HeapMaximum
cout << "当前最大的元素是: " << endl;
cout << HeapMaximum(arr) << endl << endl;
// 使用HeapExtractMax
cout << "使用HeapExtractMax后: " << endl;
HeapExtractMax(arr,heapsize);
PrintArray(arr, heapsize);
// 再次使用HeapExtractMax
cout << "再次使用HeapExtractMax后: " << endl;
HeapExtractMax(arr,heapsize);
PrintArray(arr, heapsize);
// 使用HeapIncreaseKey
cout << "使用HeapIncreaseKey后: " << endl;
HeapIncreaseKey(arr, 2, 15);
PrintArray(arr, heapsize);
// 使用MaxHeapInsert
cout << "使用MaxHeapInsert后: " << endl;
MaxHeapInsert(arr, 28, heapsize);
PrintArray(arr, heapsize);
}