#include<bits/stdc++.h>
using namespace std;constint N =1e5+10;int h[N], sz;voiddown(int u){int v = u;if(u *2<= sz && h[v]> h[u *2]) v = u *2;if(u *2+1<= sz && h[v]> h[u *2+1]) v = u *2+1;if(v != u){swap(h[u], h[v]);down(v);}}intmain(){int n, m;scanf("%d %d",&n,&m);
sz = n;for(int i =1; i <= n; i ++)scanf("%d",&h[i]);for(int i = n /2; i; i --)down(i);while(m --){printf("%d ", h[1]);
h[1]= h[sz --];down(1);}return0;}
模拟堆
代码
#include<bits/stdc++.h>
using namespace std;constint N =1e5+10;int h[N], ph[N], hp[N], sz, m;//m 表示被插入的数的计数器voidheap_swap(int a,int b){swap(h[a], h[b]);swap(ph[hp[a]], ph[hp[b]]);swap(hp[a], hp[b]);}voiddown(int u){int t = u;if(u *2<= sz && h[t]> h[u *2]) t = u *2;if(u *2+1<= sz && h[t]> h[u *2+1]) t = u *2+1;if(u != t){heap_swap(u, t);down(t);}}voidup(int u){while(u /2>0&& h[u]< h[u /2]){heap_swap(u, u /2);
u = u /2;}}intmain(){int n; cin >> n;
string op;int k, x;while(n --){
cin >> op;if(op =="I"){
cin >> x;
h[++ sz]= x;
ph[++ m]= sz;
hp[sz]= m;up(sz);}elseif(op =="PM"){
cout << h[1]<< endl;}elseif(op =="DM"){heap_swap(1, sz);
sz --;down(1);}elseif(op =="D"){
cin >> k;
k = ph[k];//注意这里是删除第 k 个插入的那个数,所以我们通过ph[] 来获取的这个数在数组中的下表为 ph[k]heap_swap(k, sz);
sz --;down(k);up(k);}elseif(op =="C"){
cin >> k >> x;
k = ph[k];
h[k]= x;down(k);up(k);}}return0;}
堆排序代码#include <bits/stdc++.h>using namespace std;const int N = 1e5 + 10;int h[N], sz;void down(int u){ int v = u; if (u * 2 <= sz && h[v] > h[u * 2]) v = u * 2; if (u * 2 + 1 <= sz && h[v] > h[u * 2 +