A15 堆 堆排序
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int a[1000010],cnt; void up(int u){ //上浮 if(u/2 && a[u/2]>a[u]) swap(a[u],a[u/2]), up(u/2); } void down(int u){ //下沉 int v=u; if(u*2<=cnt && a[u*2]<a[v]) v=u*2; if(u*2+1<=cnt && a[u*2+1]<a[v]) v=u*2+1; if(u!=v) swap(a[u],a[v]), down(v); } void push(int x){ //压入 a[++cnt]=x; up(cnt); } void pop(){ //删除 a[1]=a[cnt--]; down(1); } int main(){ int n; scanf("%d",&n); //操作次数 while(n--){ int op,x; scanf("%d",&op); if(op==1) scanf("%d",&x), push(x); else if(op==2) printf("%d\n",a[1]); else pop(); } }
// STL代码 #include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; priority_queue<int,vector<int>,greater<int> > q; int main(){ int n; scanf("%d",&n); //操作次数 while(n--){ int op,x; scanf("%d",&op); if(op==1) scanf("%d",&x), q.push(x); else if(op==2) printf("%d\n",q.top()); else q.pop(); } }
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int a[100010],cnt; void up(int u){ //上浮 if(u/2 && a[u/2]>a[u]) swap(a[u],a[u/2]), up(u/2); } void down(int u){ //下沉 int v=u; if(u*2<=cnt && a[u*2]<a[v]) v=u*2; if(u*2+1<=cnt && a[u*2+1]<a[v]) v=u*2+1; if(u!=v) swap(a[u],a[v]), down(v); } void push(int x){ //压入 a[++cnt]=x; up(cnt); } void pop(){ //删除 a[1]=a[cnt--]; down(1); } int main(){ int n; scanf("%d",&n); for(int i=1,x;i<=n;i++) scanf("%d",&x), push(x); //建堆:从堆尾插入每个数,上浮调整 for(int i=1;i<=n;i++) printf("%d ",a[1]), pop(); }
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int a[100010],cnt; void down(int u){ //下沉 int v=u; if(u*2<=cnt && a[u*2]<a[v]) v=u*2; if(u*2+1<=cnt && a[u*2+1]<a[v]) v=u*2+1; if(u!=v) swap(a[u],a[v]), down(v); } void pop(){ //删除 a[1]=a[cnt--]; down(1); } int main(){ int n; scanf("%d",&n); cnt=n; for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=n/2;i;i--) down(i); //建堆:逆序枚举每个父节点,下沉调整 for(int i=1; i<=n; i++) printf("%d ",a[1]), pop(); }
// STL代码 #include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; priority_queue<int,vector<int>,greater<int> > q; int main(){ int n; scanf("%d",&n); for(int i=1,x;i<=n;i++) scanf("%d",&x), q.push(x); //建堆 for(int i=1;i<=n;i++) printf("%d ",q.top()), q.pop(); }