1. 程式人生 > >poj1442(treap求第k大)

poj1442(treap求第k大)

syn div gcd += ace str while pre clu

ac代碼:

#include<bits/stdc++.h>
using namespace std;
#define per(i,a,b) for(int i=a;i <= b;i++)
#define Max(a,b) a=max(a,b)
#define Min(a,b) a=min(a,b)
#define Sz(x) (int)x.size()
typedef long long ll;
ll gcd(ll a,ll b){while(b){ll t=b;b=a%b;a=t;} return a;}
const int inf=0x3f3f3f3f;
#define siz 30005 int m,n,num[siz],qr[siz],ord; struct TreapNode { int rnd,sz; TreapNode*child[2]; int v; TreapNode(int val):v(val){ rnd=rand(); child[0]=child[1]=NULL; sz=1; } void update(){sz=1; if(child[0]!=NULL)sz+=child[0]->sz; if(child[1
]!=NULL)sz+=child[1]->sz;} }*root,*tmp; void Rotate(TreapNode*&u,int type) { tmp=u->child[type^1]; u->child[type^1]=tmp->child[type]; tmp->child[type]=u; u->update(); u=tmp; u->update(); } void Insert(TreapNode*&u,int val) { if(u==NULL){ u
=new TreapNode(val); } else { int type=val > u->v; Insert(u->child[type],val); if(u->child[type]->rnd > u->rnd)Rotate(u,type^1); } u->update(); } void k_th(TreapNode*u,int k)//按照ord的數字找 { if(k==1&&u->child[0]==NULL){printf("%d\n",u->v);return;} if(u->child[0]==NULL)return k_th(u->child[1],k-1); if(u->child[0]->sz == k-1){ printf("%d\n",u->v); return; } if(u->child[0]->sz < k-1)return k_th(u->child[1],k - u->child[0]->sz - 1); else if(u->child[0]->sz > k-1)return k_th(u->child[0],k); } void Print(TreapNode*u) { if(u==NULL)return; Print(u->child[0]); printf("%d ",u->v); Print(u->child[1]); } int main() { std::ios::sync_with_stdio(false); root=tmp=NULL; while(scanf("%d %d",&m,&n)!=EOF){ ord=0; per(i,1,m)scanf("%d",&num[i]); qr[0]=0; for(int i=1;i<=n;i++){ scanf("%d",&qr[i]); for(int j=qr[i-1]+1;j<=qr[i];j++){ Insert(root,num[j]); //printf("root:%d ",root->v);Print(root);printf("\n"); } ord++; k_th(root,ord); } } return 0; } /* 9 5 5 2 1 4 8 6 3 9 7 1 3 5 9 9 */

poj1442(treap求第k大)