注意:
手写堆的本质是一颗完全二叉树;
因为要维护堆的单调性,所以插入新数时放在数的最后,然后将树遍历一遍把插入的数放到满足单调性的位置(小根堆:根结点最小;反之则为大根堆)
在删除根结点(或任一元素)时用末尾元素将其覆盖,然后元素数减一
堆排序
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,m;
int s;
int a[N];
void down(int u){
int k=u;
if(u*2<=s&&a[u*2]<a[k])k=u*2;
if(u*2+1<=s&&a[u*2+1]<a[k])k=u*2+1;
if(k!=u){
swap(a[k],a[u]);
down(k);
}
}
int main(){
scanf("%d%d", &n, &m);
for(int i=1;i<=n;i++)scanf("%d", &a[i]);
s=n;
for(int i=n/2;i;i--)down(i);
while(m--){
printf("%d ", a[1]);
a[1]=a[s];
s--;
down(1);
}
return 0;
}
模拟堆
h[x] 表示树中位置 x 的元素
ph[k] = x 表示第 k 个插入的元素在树中存放的位置 x
此时如果要交换 ph 中的两个元素需要知道树中位置 x 是第几个被插入的, 于是便引入了数组 hp
hp[x] = k 表示树中位置 x 存放的为第 k 个插入的元素
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int cnt;
int h[N],ph[N],hp[N];
void swa(int a,int b){
swap(ph[hp[a]],ph[hp[b]]);
swap(hp[a],hp[b]);
swap(h[a],h[b]);
}
void down(int u){
int k=u;
if(u*2<=cnt&&h[u*2]<h[k])k=u*2;
if(u*2+1<=cnt&&h[u*2+1]<h[k])k=u*2+1;
if(k!=u){
swa(k,u);
down(k);
}
}
void up(int u){
while(u/2&&h[u/2]>h[u])swa(u,u/2),u>>=1;
}
int main(){
int n,m=0;
scanf("%d", &n);
while(n--){
char op[5];
int k,x;
scanf("%s", op);
if(!strcmp(op,"I")){
scanf("%d",&x);
cnt++;//总数
m++;//记录第几次插入
ph[m]=cnt,hp[cnt]=m;
//ph[k] = x 表示第 k 个插入的元素在树中存放的位置 x,
//hp[x] = k 表示树中位置 x 存放的为第 k 个插入的元素
h[cnt]=x;
up(cnt);
}
else if(!strcmp(op,"PM")) printf("%d\n", h[1]);
else if(!strcmp(op,"DM")){
swa(1,cnt);
cnt--;
down(1);
}
else if(!strcmp(op,"D")){
cin>>k;
k=ph[k];//找到第k个插入的数
swa(k,cnt);
cnt--;
up(k);
down(k);
}
else{
cin>>k>>x;
k=ph[k];
h[k]=x;
up(k);
down(k);
}
}
return 0;
}