特点
- 采用数组模拟堆结构
- 当前节点标号为t,左儿子为2t,右儿子为2t+1
两个操作构成其他操作的子操作
- down:cur节点与最小的子节点交换,递归向下,调整堆结构
- up: cur节点与父节点比较,递归向上,调整堆结构
支持的操作
- 添加一个元素
- 删除一个元素
- heap[k]=heap[size], down(k), up(k)
- 修改一个元素
- heap[k]=val, down(k), up(k)
- 返回最小元素
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,m;
int h[N], tot;
void down(int u){
int t=u;
if(2*u<=tot && h[2*u]<h[t]) t=2*u;
if(2*u+1<=tot && h[2*u+1]<h[t]) t=2*u+1;
if(t!=u){
swap(h[t], h[u]);
down(t);
}
}
void up(int u){
if(u<=1) return;
int t=u/2;
if(h[u]<h[t]){
swap(h[u], h[t]);
up(t);
}
}
int main(){
cin>>n>>m;
// 建堆
for(int i=0; i<n; i++){
int t;
cin>>t;
h[++tot]=t;
up(tot);
down(tot);
}
while(m--){
cout<<h[1]<<' ';
h[1]=h[tot];
--tot;
down(1);
}
}