splay第一道题,没什么感想。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 const int maxn=1000010; 6 int pre[maxn],ch[maxn][2],key[maxn]; 7 int root,tot; 8 void newnode(int &r,int fa,int k) 9 { 10 r=++tot; 11 pre[r]=fa; 12 key[r]=k; 13 ch[r][1]=ch[r][0]=0; 14 } 15 void initi() 16 { 17 root=tot=0; 18 } 19 void rotate(int x,int k) 20 { 21 int y=pre[x]; 22 ch[y][!k]=ch[x][k]; 23 pre[ch[x][k]]=y; 24 if(pre[y]) 25 ch[pre[y]][ch[pre[y]][1]==y]=x; 26 pre[x]=pre[y]; 27 ch[x][k]=y; 28 pre[y]=x; 29 } 30 void splay(int r,int goal) 31 { 32 while(pre[r]!=goal) 33 { 34 if(pre[pre[r]]==goal) 35 rotate(r,ch[pre[r]][0]==r); 36 else 37 { 38 int y=pre[r]; 39 int k=ch[pre[y]][0]==y; 40 if(ch[y][k]==r) 41 { 42 rotate(r,!k); 43 rotate(r,k); 44 } 45 else 46 { 47 rotate(y,k); 48 rotate(r,k); 49 } 50 } 51 } 52 if(goal==0) root=r; 53 } 54 void insert(int k) 55 { 56 int r=root; 57 if(r==0) 58 { 59 newnode(root,0,k); 60 return ; 61 } 62 while(ch[r][key[r]<k]) 63 r=ch[r][key[r]<k]; 64 newnode(ch[r][key[r]<k],r,k); 65 splay(ch[r][key[r]<k],0); 66 } 67 int Getpre(int r) 68 { 69 if(ch[r][0]==0) return -1; 70 r=ch[r][0]; 71 while(ch[r][1]) r=ch[r][1]; 72 return key[r]; 73 } 74 int Getsuf(int r) 75 { 76 if(ch[r][1]==0) return -1; 77 r=ch[r][1]; 78 while(ch[r][0]) r=ch[r][0]; 79 return key[r]; 80 } 81 int main() 82 { 83 int n; 84 while(scanf("%d",&n)==1) 85 { 86 initi(); 87 int x; 88 int ans=0; 89 while(n--) 90 { 91 if(scanf("%d",&x)==EOF) x=0; 92 insert(x); 93 int a=Getpre(root); 94 int b=Getsuf(root); 95 if(a!=-1&&b!=-1) 96 ans+=min(x-a,b-x); 97 else if(a!=-1&&b==-1) 98 ans+=x-a; 99 else if(a==-1&&b!=-1) 100 ans+=b-x; 101 else 102 ans+=x; 103 } 104 printf("%d ",ans); 105 } 106 }