Heap && Priority_Queue

本文介绍了一种最大堆及由其构成的优先队列的实现方式,并提供了详细的算法流程,包括Max-Heapify、Build-Max-Heap、HeapSort等核心函数,以及插入、删除最大元素和增加键值等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//最大堆以及由最大堆构成的优先队列
//data:length,heap-size
//element-handle(元素柄,记录元素的位置,可用HashTable实现)
//function: inline: Parent(i),Left(i),Right(i)  (O(1))
//Max-Heapify(i)(O(lgn)),Build-Max-Heap(O(n))
//HeapSort O(nlgn)
//Maximum(O(1)),Extract-Max(O(lgn)),Increase-Key(S,x,k)(O(lgn)),Insert(S,x)O(lgn))
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define maxn 1005
#define INF 0xfffffff
#define Parent(i) (i)>>1
#define Left(i) (i)<<1
#define Right(i) ((i)<<1)+1
int A[maxn],length,heap_size;
void Max_Heapify(int i)  //down
{
    int l=Left(i),r=Right(i),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)
    {
        swap(A[i],A[largest]);
        Max_Heapify(largest);
    }
}
void Build_Max_Heap()
{
    heap_size=length;
    int i;
    for(i=length/2;i>0;--i)
        Max_Heapify(i);
}
void HeapSort()
{
    Build_Max_Heap();
    int i;
    for(i=length;i>1;--i)
    {
        swap(A[1],A[i]);
        heap_size--;
        Max_Heapify(1);
    }
}
int Heap_Maximum()
{
    return A[1];
}
int Heap_Extract_Max()
{
    assert(heap_size>0);
    int Max=A[1];
    A[1]=A[heap_size--];
    Max_Heapify(1);
    return Max;
}
void Heap_Increase_Key(int i,int key) //up
{
    assert(key>A[i]);
    A[i]=key;
    while(i>1&&A[Parent(i)]<A[i])
    {
        swap(A[i],A[Parent(i)]);
        i=Parent(i);
    }
}
void Max_Heap_Insert(int key)
{
    heap_size++;
    A[heap_size]=-1*INF;
    Heap_Increase_Key(heap_size,key);
}         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值