Http://www.lydsy.com/JudgeOnline/problem.php? Id = 1588
# Include <cstdio> # include <cstdlib> const int mod = 1000000; const int INF = ~ 0u> 2; # define kt (CH [CH [RT] [1] [0]) const int maxn = 200010; int ans; struct splaytree {int SZ [maxn]; int ch [maxn] [2]; int pre [maxn]; int RT, top; inline void up (int x) {SZ [x] = CNT [x] + SZ [CH [x] [0] + SZ [CH [x] [1];} inline void rotate (int x, int f) {int y = pre [X]; ch [y] [! F] = CH [x] [f]; Pre [CH [x] [f] = y; Pre [x] = pre [y]; if (pre [x]) CH [pre [y] [CH [pre [y] [1] = y] = X; ch [x] [f] = y; Pre [y] = x; up (y);} inline void splay (int x, int goal) {// rotate X under goal while (pre [x]! = Goal) {If (pre [pre [x] = goal) rotate (x, CH [pre [x] [0] = X ); else {int y = pre [X], Z = pre [y]; int F = (CH [Z] [0] = y ); if (CH [y] [f] = x) rotate (x ,! F), rotate (x, f); else rotate (Y, F), rotate (x, f) ;}} up (x); If (Goal = 0) RT = x;} inline void RTO (int K, int goal) {// rotate the K-digit to the bottom of Goal int x = RT; while (SZ [CH [x] [0]! = K-1) {If (k <SZ [CH [x] [0] + 1) x = CH [x] [0]; else {k-= (SZ [CH [x] [0] + 1); X = CH [x] [1] ;}} splay (x, goal );} inline void vist (int x) {If (x) {printf ("Node % 2D: Left son % 2D right son % 2D % 2D SZ = % d \ n", X, ch [x] [0], CH [x] [1], Val [X], SZ [x]); vist (CH [x] [0]); vist (CH [x] [1]) ;}} inline void newnode (Int & X, int c) {x = ++ top; ch [x] [0] = CH [x] [1] = pre [x] = 0; SZ [x] = 1; CNT [x] = 1; val [x] = C;} inline void Init () {ans = 0; ch [0] [0] = CH [0] [1] = pre [0] = SZ [0] = 0; RT = Top = 0; CNT [0] = 0; newnode (RT,-INF); newnode (CH [RT] [1], INF); Pre [Top] = RT; SZ [RT] = 2 ;} inline void insert (Int & X, int key, int f) {If (! X) {newnode (x, key); Pre [x] = f; splay (x, 0); // efficiency assurance return ;} if (Key = Val [x]) {CNT [x] ++; SZ [x] ++; splay (x, 0); // timeout when no value is added, else ah return;} else if (Key <Val [x]) {insert (CH [x] [0], key, x );} else {insert (CH [x] [1], key, x);} Up (x);} void findpre (int x, int key, Int & ANS) {If (! X) return; If (Val [x] <= Key) {ans = Val [X]; findpre (CH [x] [1], key, ANS );} else findpre (CH [x] [0], key, ANS);} void findsucc (int x, int key, Int & ANS) {If (! X) return; If (Val [x]> = Key) {ans = Val [X]; findsucc (CH [x] [0], key, ANS );} else findsucc (CH [x] [1], key, ANS) ;}void solve () {int num; num = 0; scanf ("% d", & num ); int X, Y; findpre (RT, num, x); findsucc (RT, num, Y); If (ABS (X-num) <= ABS (Y-num )) {If (X! =-INF) ans + = ABS (X-num);} else {If (y! = Inf) ans + = ABS (Y-num);} insert (RT, num, 0);} int CNT [maxn]; int Val [maxn];} SPT; int main () {int N; scanf ("% d", & N); SPT. init (); ans = 0; scanf ("% d", & ANS); SPT. insert (SPT. RT, ANS, 0); n --; while (n --) {SPT. solve ();} printf ("% d \ n", ANS); Return 0 ;}