标签:
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3456 Accepted Submission(s): 1493
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 using namespace std; 6 const int maxn=100010; 7 int n,fa[maxn],ch[maxn][2],sz[maxn]; 8 int flip[maxn],pos[maxn],rt; 9 struct Node{ 10 int x,id; 11 }a[maxn]; 12 13 void Flip(int x){ 14 swap(ch[x][0],ch[x][1]); 15 flip[x]^=1; 16 } 17 18 void Push_down(int x){ 19 if(flip[x]){ 20 Flip(ch[x][0]); 21 Flip(ch[x][1]); 22 flip[x]=0; 23 } 24 } 25 26 int pd[maxn]; 27 void P(int x){ 28 int cnt=0; 29 while(x){ 30 pd[++cnt]=x; 31 x=fa[x]; 32 } 33 while(cnt){ 34 Push_down(pd[cnt--]); 35 } 36 } 37 38 void Push_up(int x){ 39 sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+1; 40 } 41 42 void Rotate(int x){ 43 int y=fa[x],g=fa[y],c=ch[y][1]==x; 44 ch[y][c]=ch[x][c^1];fa[ch[x][c^1]]=y; 45 ch[x][c^1]=y;fa[y]=x;fa[x]=g; 46 if(g)ch[g][ch[g][1]==y]=x; 47 Push_up(y); 48 } 49 50 void Splay(int x,int g=0){ 51 P(x); 52 for(int y;(y=fa[x])!=g;Rotate(x)) 53 if(fa[y]!=g) 54 Rotate((ch[fa[y]][1]==y)==(ch[y][1]==x)?y:x); 55 Push_up(x); 56 if(!g)rt=x; 57 } 58 59 int Build(int f,int l,int r){ 60 if(l>r)return 0; 61 int mid=(l+r)>>1;fa[mid]=f; 62 ch[mid][0]=Build(mid,l,mid-1); 63 ch[mid][1]=Build(mid,mid+1,r); 64 sz[mid]=1; 65 Push_up(mid); 66 return mid; 67 } 68 69 bool cmp(Node a,Node b){ 70 if(a.x!=b.x) 71 return a.x<b.x; 72 return a.id<b.id; 73 } 74 75 int main(){ 76 while(~scanf("%d",&n)&&n){ 77 memset(flip,0,sizeof(flip)); 78 rt=Build(0,1,n+2); 79 for(int i=1;i<=n;i++) 80 scanf("%d",&a[i].x); 81 for(int i=1;i<=n;i++) 82 a[i].id=i; 83 sort(a+1,a+n+1,cmp); 84 for(int i=1;i<=n;i++) 85 pos[i+1]=a[i].id+1; 86 pos[1]=1;pos[n+2]=n+2; 87 for(int i=2,p;i<n+1;i++){ 88 Splay(pos[1]); 89 Splay(pos[i],pos[1]); 90 printf("%d ",sz[ch[ch[rt][1]][0]]+1); 91 Splay(pos[i]); 92 p=ch[pos[i]][1]; 93 while(ch[p][0]){ 94 Push_down(p); 95 p=ch[p][0]; 96 } 97 Push_down(p); 98 Splay(pos[i-1]); 99 Splay(p,pos[i-1]); 100 Flip(ch[ch[rt][1]][0]); 101 } 102 printf("%d\n",n); 103 } 104 return 0; 105 }
数据结构(Splay平衡树):HDU 1890 Robotic Sort
标签:
原文地址:http://www.cnblogs.com/TenderRun/p/5352761.html