用数组模拟堆——手写大根堆、小根堆模板

了解什么是堆?
小根堆排序模板

大根堆排序

实现的五个基本功能:

  1. 插入一个数:heap[++sz]=x; up(sz); 尾部插入
  2. 求集合中的最大值:heap[1]
  3. 删除最大值:heap[1]=heap[sz]; sz– – ; down(1); 尾部代替头部
  4. 删除任一个结点为k的元素:heap[k]=heap[sz]; sz– – ; down(k); up(k);
  5. 修改任一个结点为k的元素:heap[k]=x; down(k); up(k);

还有一个初始化功能,可直接依靠down函数

#include <iostream>

using namespace std;

const int N=1e5+10;
int heap[N],sz;
//编号从1开始,因此也从下标1开始存数

void down(int x)//结点编号为x,功能,选择父结点x,左孩子x*2,右孩子x*2+1 中最大的作为父结点
{
    
    
    int t=x;
    if (x*2<=sz && heap[t]<heap[x*2]) t=x*2;
    if (x*2+1<=sz && heap[t]<heap[x*2+1]) t=x*2+1;
    if (x!=t) {
    
    
        swap(heap[t],heap[x]);
        down(t);
    }
}

void up(int x)//判断当前节点x是否大于父结点x/2,是则换
{
    
    
    while (x/2 && heap[x] > heap[x/2]) {
    
    
        swap(heap[x/2],heap[x]);
        x/=2;
    }
}

void del_x(int x)  //删除结点为x的结点,包括头结点在内
{
    
    
    heap[x]=heap[sz--];
    down(x);
    up(x);  //down和up其中只会执行一个。
}

void rep_x(int x,int num)  //替换结点为x的结点的值,包括头结点在内
{
    
    
    heap[x]=num;
    down(x);
    up(x);
}

int main() {
    
    
    int n;
    scanf("%d",&n);
    for (int i = 1; i <= n; ++i)    scanf("%d",heap+i);
    sz=n;
    for (int i = n/2; i >= 1; --i)  down(i);
    while (n--){
    
    
        cout<<heap[1]<<" ";
        del_x(1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HangHug_L/article/details/113770918
今日推荐