【堆】小根堆模板
阿新 • • 發佈:2017-10-15
esp printf 最小值 namespace 記得 class queue 二叉 %d
手寫堆
可以視作是一種完全二叉樹結構
#include<iostream> #include<cstring> #include<algorithm> #include<cstdio> using namespace std; const int Maxn=1000005; int sta[Maxn]; int n,tot=0;//tot記錄元素總數,記得及時更新 inline int read() { int x=0,w=1; char ch=0; while(ch!=‘-‘ && (ch<‘0‘ || ch>‘9‘)) ch=getchar(); if(ch==‘-‘) w=-1,ch=getchar(); while(ch>=‘0‘ && ch<=‘9‘) x=x*10+ch-‘0‘,ch=getchar(); return x*w; } inline void push(int b) { sta[++tot]=b; for(int i=tot,j=i>>1; j; i=j,j=i>>1) { if(sta[j]>sta[i]) swap(sta[j],sta[i]); //只需要判斷當前節點與父親的大小關系 } } inline void pop() { sta[1]=sta[tot--];//最小值覆蓋掉 for(int i=1,j=i<<1; j<=tot; i=j,j=i<<1) { if(j+1<=tot&&sta[j+1]<sta[j]) j++;//因為是小根堆,所以在兩個兄弟節點之間選取更小的那個向上推 if(sta[i]<sta[j]) break;//此時沒有交換的必要 else swap(sta[i],sta[j]); } } int main() { n=read(); int a,b; for(int i=1; i<=n; i++) { a=read(); if(a==1) { b=read(); push(b); } else if(a==2) printf("%d\n",sta[1]); else if(a==3) pop(); } return 0; }
STL
可以用優先隊列
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<queue> using namespace std; priority_queue <int> q;//定義堆 int n; int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { int opt,x; scanf("%d",&opt); if(opt==1) scanf("%d",&x),q.push(-x);//加負號 if(opt==2) printf("%d\n",-q.top());//加負號 if(opt==3) q.pop(); } return 0; }
【堆】小根堆模板