优先队列

来源:互联网 发布:淘宝童装排名 编辑:程序博客网 时间:2024/06/11 18:52
//优先队列,基于最大堆实现最大优先队列,在数组中实现,其关键字(key)为数组元素//数组元素下标为句柄(handle)//在最大堆和最大优先队列中数组下标都是从1开始,为了维持其父母孩子的相对位置关系#include <iostream>#define PARENT(i) i>>1;#define LEFT(i) i<<1;#define RIGHT(i) (i<<1)+1const int MIN=1<<(sizeof(int)*8-1);using namespace std;void MAX_HEAPIFY(int A[],int heap_size,int i)  //维护堆的性质{    int l,r;    l=LEFT(i);    r=RIGHT(i);    int largest;    if(l<=heap_size && A[l]>A[i]) largest=l;    else largest=i;    if(r<=heap_size && A[r]>A[largest]) largest=r;    if(largest != i)    {        int temp;        temp=A[largest];        A[largest]=A[i];        A[i]=temp;        MAX_HEAPIFY(A,heap_size,largest);    }    return ;}void HEAP_INCREASE_KEY(int A[],int x,int k);void HEAP_INSERT(int A[],int heap_size,int x)   //将x插入队列A[]中{    heap_size++;    A[heap_size]=MIN;    HEAP_INCREASE_KEY(A,heap_size,x);}int HEAP_MAXIMUM(int A[]) //返回具有最大关键字的元素{   return A[1];}int HEAP_EXTRACT_MAX(int A[],int heap_size) //去掉A[]中的最大关键字并返回最大关键字{    if(heap_size<1) cout<<"heap_size<1"<<endl;    int max;    max=A[1];    A[1]=heap_size;    heap_size--;    MAX_HEAPIFY(A,heap_size,1);    return max;}void HEAP_INCREASE_KEY(int A[],int x,int k)  //增加句柄(x)所在的关键字的优先级,也就是将A[x]替换为k值,k>=A[x]{    if(k<A[x]) cout<<"k wrong"<<endl;    A[x]=k;    while(1)    {        int temp=PARENT(x);        if(x>1 && A[temp]<A[x])        {            int exchange=A[temp];            A[temp]=A[x];            A[x]=exchange;            x=temp;        }        else break;    }}int main(int argc, char *argv[]){    int test[11]={0,16,14,10,8,7,9,3,2,4,1};    cout<<HEAP_MAXIMUM(test)<<endl;    HEAP_INCREASE_KEY(test,10,20);    cout<<test[1]<<endl;    cout<<HEAP_EXTRACT_MAX(test,10)<<endl;    cout<<test[1]<<endl;    cout << "Hello World!" << endl;    return 0;}