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