堆与堆排序

  • 堆是一个完全二叉树,完全二叉树就是二叉树除了最后一层外均为满的,最后一层从有向左排列。
  • 堆分为小根堆和大根堆。小根堆的根节点小于左右两个节点,大根堆相反。
堆的相关操作

down操作

void down(int u){
	 int t = u;
	 if(u*2<=size&&h[t]>h[u*2])t = u*2;
	 if(u*2+1<=size&&h[t]>h[u*2+1])t = u*2+1;
	 if(t!=u){
	 	swap(h[u],h[t]);
	 	down(t);
	 }
}

建堆时 O ( n ) O(n) O(n)复杂度操作

for(int i=n/2;i;i--){
	down(i);
}

up操作

void up(int u){
	while(u/2&&h[u/2]>h[u]){
		swap(h[u],h[u/2]);
		u /= 2;
	}
}

特殊情况,调整第k个插入的元素

void heap_swap(int a,int b){//ph存储第k个元素在堆中的位置下标,hp存储堆中小标对应的第几个元素。
    swap(h[a],h[b]);
    swap(ph[hp[a]],ph[hp[b]]);
    swap(hp[a],hp[b]);
}

如模拟堆的模板题
模拟堆

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int h[N],ph[N],hp[N];
int cnt;

void heap_swap(int a,int b){
    swap(h[a],h[b]);
    swap(ph[hp[a]],ph[hp[b]]);
    swap(hp[a],hp[b]);
}

void down(int u){
    int t = u;
    if(u*2<=cnt&&h[t]>h[u*2])t = u*2;
    if(u*2+1<=cnt&&h[t]>h[u*2+1])t = u*2+1;
    if(t!=u){
        heap_swap(u,t);
        down(t);
    }
}

void up(int u){
    while(u/2&&h[u/2]>h[u]){
        heap_swap(u,u/2);
        u /= 2;
    }
}



int main()
{
    int n;
    int m = 0;
    char op[3];
    int k,x;
    scanf("%d",&n);
    while(n--){
        scanf("%s",op);
        if(op[0]=='I'){
            scanf("%d",&x);
            m++;//记录第几个元素
            h[++cnt] = x;
            ph[m] = cnt;
            hp[cnt] = m;
            up(cnt);
        }
        else if(op[0]=='P'&&op[1]=='M'){
            printf("%d\n",h[1]);
        }
        else if(op[0]=='D'&&op[1]=='M'){
            heap_swap(cnt,1);
            cnt--;
            down(1);
        }
        else if(op[0]=='D'){
            scanf("%d",&k);
            int u = ph[k];
            heap_swap(ph[k],cnt);//up或down时一定是操作堆中的下标,交换也是。
            cnt--;
            down(u),up(u);
        }
        else{
            scanf("%d%d",&k,&x);
            int u = ph[k];
            h[u] = x;
            up(u),down(u);
        }
    }
    return 0;
}

堆的相关操作

  • 插入一个元素,就是在堆末尾插入,然后进行up操作。
  • 删除一个元素,将该元素与最后一个元素交换,然后down操作。
  • 改变一个元素,down或up操作必进行一个。
  • 取最小或最大值即为heap[1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

up-to-star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值