To learn a little bit of splay template, not so difficult to imagine, mainly left-and right-handed can be simplified to a function inside, reduce code length ...
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 #defineMAXN 333336 #defineINF 0x3f3f3f3f7 #defineLC (x) ch[(x)][0]8 #defineRC (x) ch[(x)][1]9 using namespacestd;Ten intfa[maxn],ch[maxn][2],root,k[maxn],ind=1; OneInlinevoidRotateintp) A { - intq=fa[p],y=fa[q],x=ch[q][1]==p; -ch[q][x]=ch[p][x^1];fa[ch[q][x]]=Q; thech[p][x^1]=q;fa[q]=p; -fa[p]=y; - if(y) - { + if(ch[y][0]==Q) ch[y][0]=p; - Elsech[y][1]=p; + } A } atInlinevoidSplay (intx) - { - for(inty;y=fa[x];rotate (x)) - { - if(Fa[y]) - { in if(Y==LC (Fa[y]) &&x==lc (y) | | (Y==RC (Fa[y]) &&x==RC (y))) Rotate (y); - Elserotate (x); to } + } -root=x; the } * voidInsertintXintv) $ {Panax Notoginseng while(Ch[x][k[x]<v]) x=ch[x][k[x]<v]; -ch[x][k[x]<v]=++IND; thefa[ind]=x;k[ind]=V;splay (Ind); + } AInlineintPreintx) the { + inttmp=ch[x][0]; - while(ch[tmp][1]) tmp=ch[tmp][1]; $ returnk[tmp]; $ } -InlineintSucintx) - { the inttmp=ch[x][1]; - while(ch[tmp][0]) tmp=ch[tmp][0];Wuyi returnk[tmp]; the } - intMain () Wu { - intTintN; About intans=0; $scanf"%d",&n); - if(SCANF ("%d", &t) ==-1) t=0; -root=1; k[root]=T; -ans=T; AInsert (Root,inf); Insert (root,-inf); + for(intI=2; i<=n;i++) the { - if(SCANF ("%d", &t) ==-1) t=0; $ Insert (root,t); the intA=pre (root);intb=suc (root); theAns+=min (t-a,b-t); the } theprintf"%d\n", ans); - return 0; in}
Bzoj 1588 splay Template problem