标签:des style blog http color io os ar java
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2495 Accepted Submission(s): 1107
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; #define N 100100 struct node { int pos,val; }num[N]; int mp[N]; int val[N]; int reflect[N]; bool cmp(node a,node b) { if(a.val!=b.val) return a.val<b.val; return a.pos<b.pos; } struct SplayTree { int ch[N][2],pre[N],size[N],lazy[N]; int root,top; void PushUp(int x) { size[x]=size[ch[x][0]]+size[ch[x][1]]+1; } void PushDown(int x) { if(lazy[x]) { swap(ch[x][0],ch[x][1]); lazy[ch[x][0]]^=1; lazy[ch[x][1]]^=1; lazy[x]=0; } } void Rotate(int x,int c) { int y=pre[x]; PushDown(y); PushDown(x); ch[y][!c]=ch[x][c]; if(ch[x][c]) pre[ch[x][c]]=y; pre[x]=pre[y]; if(pre[y]) ch[pre[y]][ch[pre[y]][1]==y]=x; ch[x][c]=y; pre[y]=x; PushUp(y); } void Splay(int x,int f) { PushDown(x); while(pre[x]!=f) { PushDown(pre[pre[x]]); PushDown(pre[x]); PushDown(x); if(pre[pre[x]]==f) Rotate(x,ch[pre[x]][0]==x); else { int y=pre[x]; int z=pre[y]; int c=(ch[z][0]==y); if(ch[y][c]==x) { Rotate(x,!c); Rotate(x,c); } else { Rotate(y,c); Rotate(x,c); } } } PushUp(x); if(f==0) root=x; } void Splay_Kth(int k,int f) { int x=root; PushDown(x); while(1) { if(k==size[ch[x][0]]+1) break; else if(k<size[ch[x][0]]+1) x=ch[x][0]; else { k-=size[ch[x][0]]+1; x=ch[x][1]; } PushDown(x); } Splay(x,f); } void Newnode(int &x) { x=++top; ch[x][0]=ch[x][1]=pre[x]=lazy[x]=0; size[x]=1; } void Build(int &x,int l,int r,int f) { if(l>r) return; int m=(l+r)>>1; Newnode(x); val[x]=num[reflect[m]].val; mp[reflect[m]]=x; //建立映射 Build(ch[x][0],l,m-1,x); Build(ch[x][1],m+1,r,x); pre[x]=f; PushUp(x); } void Init(int n) { top=root=0; ch[0][0]=ch[0][1]=size[0]=pre[0]=lazy[0]=val[0]=0; Build(root,1,n,0); } void Del() { int t=root; if(ch[root][1]) { root=ch[root][1]; Splay_Kth(1,0); ch[root][0]=ch[t][0]; if(ch[root][0]) pre[ch[root][0]]=root; } else root=ch[root][0]; pre[root]=0; PushUp(root); } }t; int main() { int n,i; while(scanf("%d",&n) && n) { for(i=1;i<=n;i++) { scanf("%d",&num[i].val); num[i].pos=i; } sort(num+1,num+n+1,cmp); for(i=1;i<=n;i++) { reflect[num[i].pos]=i; } t.Init(n); for(i=1;i<=n;i++) { t.Splay(mp[i],0); int ans=i+t.size[t.ch[t.root][0]]; t.lazy[t.ch[t.root][0]]^=1; t.Del(); if(i!=1) printf(" "); printf("%d",ans); } printf("\n"); } return 0; }
Splay练习题 [HDU 1890] Robotic Sort
标签:des style blog http color io os ar java
原文地址:http://www.cnblogs.com/hate13/p/4040710.html