堆--附帶自動排序功能
阿新 • • 發佈:2018-11-10
時間複雜度太高了
程式碼:
#include<cstdio> #include<iostream> #include<cstring> #define INF -2000000001 using namespace std; int heap[200001]; int heap_size=0; void init(){ for(int i=0;i<20001;i++) heap[i]=INF; } int twoJZ[200001]; int gettwoCF(int x){//獲取e2的盛放 if(x==0)return 1; if(x==1)return 2; if(twoJZ[x]!=-1)return twoJZ[x]; int base=2; for(int i=1;i<x;i++){ base*=2; } twoJZ[x]=base; return base; } void coutTree(){ for(int i=1;i<=heap_size;i++){ cout<<heap[i]<<" "; } cout<<endl; } int getCeng(int x){//給定一個數,獲取這個index所在的二叉樹層數 if(x==1)return 1; int now,next; now=1; while(gettwoCF(now+1)-1<x) { now++; } return now+1; } void updataFloor(int x,int now){//更新制定層數 制定的結點開始 int sum=0; for(int i=gettwoCF(x-1);i<=now;i++){ if(heap[now]<heap[i]){ swap(heap[now],heap[i]); updataFloor(x,now); return; } } } void put(int x){ heap[++heap_size]=x; int now,next; now=heap_size; while(now!=0){ next=now/2; if(heap[now]>=heap[next]){ updataFloor(getCeng(now),now); int lastFloor=getCeng(now)-1; int lastMaxINDEX=gettwoCF(lastFloor)-1; int lastFloorMaxValue=heap[lastMaxINDEX]; if(heap[now]<lastFloorMaxValue){//if(heap[now]<上一行的最大){ swap(heap[now],heap[lastMaxINDEX]);//上一行最大); updataFloor(lastFloor,lastMaxINDEX);//上一層 } return; } swap(heap[now],heap[next]); updataFloor(getCeng(now),now);//new now=next; } } void del(){ int now,next; heap[1]=heap[heap_size--]; now=1; while(now*2<=heap_size){ next=now*2; if(heap[next+1]<heap[next])next++; if(heap[next]>=heap[now])return; swap(heap[now],heap[next]); now=next; } } int get(int index){//獲取第幾小的數 return heap[index]; } int a[200001];//A操作 int u[200001];//u操作 int ucnt=0;//u操作的計數 int mttl=0;//已經存元素的數量 int main(){ init(); memset(twoJZ,-1,sizeof(twoJZ)); //updataFloor(3,4); int m,n; cin>>m>>n; for(int i=1;i<=m;i++){ int temp; cin>>temp; a[i]=temp; } for(int i=1;i<=n;i++){ int temp; cin>>temp; u[i]=temp; } while(mttl<m){ put(a[++mttl]); while(u[ucnt+1]==mttl){ int getValue=get(++ucnt); cout<<getValue<<endl; } } return 0; }