"The main topic"
[Borrowing others ' generalizations] gives an n number of sequence A, for the first element AI defines fi=min (ABS (Ai-aj)), (1<=j<i), where F1=A1. Output sum (FI) (1<=i<=n)
Ideas
The balance tree, the smallest absolute value of the unknown must be a prefix and a successor. It is important to note that because AI and AJ may be equal, that is, min may be equal to zero, add a judgment: if the key in the current balance tree is equal to the value to be found, and the current node has more than one CNT, then there is a value before the current equality. In some cases, the node you are looking for may not have a precursor or successor, and you need to be judged.
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5#include <cmath>6 using namespacestd;7 Const intinf=0x7fffffff;8 structtreap9 {Ten intkey; One intPriority ; Atreap*Lson; -treap*Rson; - intCNT; the treap () - { -key=0; -Cnt=1; + /*the initial value here is 1 .*/ -priority=rand (); +lson=rson=NULL; A } at }; -treap* root=NULL; - - voidRightrotate (treap* &RT) - { -treap* tmp=rt->Lson; inRt->lson=tmp->Rson; -tmp->rson=RT; tort=tmp; + } - the voidLeftrotate (treap* &RT) * { $Treap *tmp=rt->Rson;Panax NotoginsengRt->rson=tmp->Lson; -tmp->lson=RT; thert=tmp; + } A the voidInsert (treap* &rt,intx) + { - if(rt==NULL) $ { $rt=Newtreap; -rt->key=x; - } the Else - {Wuyi if(rt->key==x) the { -rt->cnt++; Wu } - Else if(rt->key>x) About { $Insert (rt->lson,x); - if(rt->lson->priority>rt->Priority ) Rightrotate (RT); - } - Else A { +Insert (rt->rson,x); the if(rt->rson->priority>rt->Priority ) Leftrotate (RT); - } $ } the } the the intPre (treap* &rt,intx) the { - intans=-INF; intreap* tmp=RT; the while(TMP) the { About if(Tmp->key==x && tmp->cnt>1)returnX//"Attention" This sentence is very important, do not miss out! the if(tmp->key<x) the { theAns=max (tmp->Key,ans); +Tmp=tmp->Rson; - } the ElseTmp=tmp->Lson;Bayi } the returnans; the } - - intSUC (treap* &rt,intx) the { the intans=INF; theTreap *tmp=RT; the while(TMP) - { the if(tmp->key>x) the { the if(Tmp->key==x && tmp->cnt>1)returnx;94Ans=min (Tmp->key,ans);//here the hand slip is written as Max (X,ans) Orz theTmp=tmp->Lson; the } the ElseTmp=tmp->Rson;98 } About returnans; - }101 102 intresult ()103 {104 intN,ans; the if(SCANF ("%d", &n) = = EOF) n =0;106 for(intI=0; i<n;i++)107 {108 intturnover;109 if(SCANF ("%d", &turnover) = = EOF) turnover =0; the Insert (root,turnover);111 if(i==0) the {113ans=turnover; the } the Else the {117 intPremax,sucmin,ad=INF;118premax=Pre (root,turnover);119sucmin=suc (root,turnover); - if(Premax!=-inf && Premax!=inf) ad=min (ad,turnover-Premax);121 if(Sucmin!=inf && Sucmin!=-inf) ad=min (ad,sucmin-turnover);122 if(Ad!=inf && Ad!=-inf) ans=ans+AD;123 }124 } the returnans;126 } 127 - intMain ()129 { theprintf"%d", result ());131 return 0; the}
"Treap" bzoj1588-[hnoi2002] turnover statistics