(Based on NOI2002 turnover statistics Codevs1296)
1 Constmaxn=100050;2 var3 I,j,k,l,m,n,tot,head,t:longint;ac:int64;4A,lef,rig,fix:Array[0.. MAXN] ofLongint;5 functionMax (x,y:longint): Longint;6 begin7 ifX>y ThenMax:=xElsemax:=y;8 End;9 functionmin (x,y:longint): Longint;Ten begin One ifX<y ThenMin:=xElsemin:=y; A End; - functionNEWP (x:longint): Longint; - begin theInc (TOT); a[tot]:=x; -lef[tot]:=0; rig[tot]:=0; -fix[tot]:=random (maxlongint); - exit (TOT); + End; - procedureLtvarx:longint); + varF,r:longint; A begin atf:=x;r:=Rig[x]; -rig[f]:=Lef[r]; -lef[r]:=F; -x:=R; - End; - procedureRtvarx:longint); in varF,l:longint; - begin tof:=x;l:=Lef[x]; +lef[f]:=Rig[l]; -rig[l]:=F; thex:=l; * End; $ procedureInsvarx:longint;y:longint);Panax Notoginseng begin - ifx=0 Then the begin +x:=newp (y); A exit; the End; + ifY<A[X] Then - begin $ ins (lef[x],y); $ ifFIX[LEF[X]]<FIX[X] ThenRT (x); - End - Else the begin - ins (rig[x],y);Wuyi ifFIX[RIG[X]]<FIX[X] ThenLT (x); the End; - End; Wu functionGetpre (x,y:longint): Longint; - varZ:longint; About begin $ ifx=0 ThenExit0); - ifA[x]<=y Then - begin -z:=Getpre (rig[x],y); A ifz=0 ThenExit (x)Else + ifA[Z]>A[X] ThenExit (Z)Elseexit (x); the End - Elseexit (Getpre (Lef[x],y)); $ End; the functiongetsuc (x,y:longint): Longint; the varZ:longint; the begin the ifx=0 ThenExit0); - ifA[x]>=y Then in begin thez:=getsuc (lef[x],y); the ifz=0 ThenExit (x)Else About ifA[Z]<A[X] ThenExit (Z)Elseexit (x); the End the Elseexit (GETSUC (Rig[x],y)); the End; + begin -READLN (n); tot:=0; head:=0; a[0]:=0; ac:=0; the fori:=1 toN DoBayi begin the Readln (j); thek:=Getpre (head,j); -l:=getsuc (head,j); - if((k=0) and(l=0))or((k<>0) and(l<>0)) Then theT:=min (ABS (A[K]-J), ABS (a[l]-j)) the Else ifK<>0 ThenT:=abs (A[K]-J)ElseT:=abs (a[l]-j); theac:=ac+T; the ins (head,j); - End; the Writeln (AC); the End.
Treap Balance Tree (Pascal Edition)