之前堆都是直接用stl中的priority_queue,一直不会手写堆,所以今天搞一下这个手写堆。
洛谷P3378堆的板子
#include<cstdio> #include<iostream> using namespace std; int tree[2000003],t,n; void change(int a,int b) { int temp = tree[a]; tree[a] = tree[b]; tree[b] = temp; } void del(int x) { int d = x,f = 0; while(x * 2 <= t && f == 0) { if(tree[x] > tree[x * 2] && x * 2 <= t) { d = x * 2; } if(tree[x] > tree[x * 2 + 1] && tree[x * 2 + 1] < tree[x * 2] && x * 2 + 1 <= t) { d = x * 2 + 1; } if(x != d) { change(x,d); x = d; } else f = 1; } } void insert(int x) { int d,f = 0; while(x != 1 && f == 0) { if(tree[x / 2] > tree[x]) { d = x / 2; change(x,d); } else f = 1; x = x / 2; } } int main() { scanf("%d",&n); int m,k; for(int i = 1;i <= n;i++) { scanf("%d",&m); if(m == 1) { scanf("%d",&k); t++; tree[t] = k; insert(t); } if(m == 2) { printf("%d ",tree[1]); } if(m == 3) { tree[1] = tree[t]; t--; del(1); } } return 0; }
挺好理解的。