https://www.lydsy.com/JudgeOnline/problem.php?id=1588
伸展树模板题 在这题里就是普通二叉树 只不过每次要把新插入的节点splay到根节点之下 可达到均摊nlogn 大概这就是充满玄学的局部性原理了。。
线段树或者排序乱搞都可以
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=0x3f3f3f3f3f3f3f3f;
struct node;
node *null;
struct node
{
node *ch[2],*fa;
ll val;
int sz;
void wipe()
{
fa=ch[0]=ch[1]=null;
sz=0,val=0;
}
void setc(node *tmp,int d)
{
ch[d]=tmp;
tmp->fa=this;
}
bool getd()
{
return fa->ch[1]==this;
}
void pushup()
{
sz=ch[0]->sz+ch[1]->sz+1;
}
};
node *mp[50010];
node *root,*tail;
node pool[50010];
ll ary[50010];
int n;
void init()
{
node *tmp;
int i;
tail=pool;
null=tail++;
null->fa=null->ch[0]=null->ch[1]=null;
null->sz=null->val=0;
tmp=tail++;
tmp->wipe();
root=tmp;
tmp=tail++;
tmp->wipe();
root->setc(tmp,1);
}
node *insert(node *&cur,node *fa,ll val)
{
node *res;
if(cur==null)
{
cur=tail++;
cur->wipe();
cur->fa=fa;
cur->sz=1,cur->val=val;
return cur;
}
if(val<=cur->val) res=insert(cur->ch[0],cur,val);
else res=insert(cur->ch[1],cur,val);
cur->pushup();
return res;
}
void rotate(node *cur)
{
node *f,*ff;
int c,cc;
f=cur->fa,ff=cur->fa->fa;
c=cur->getd(),cc=f->getd();
f->setc(cur->ch[!c],c);
cur->setc(f,!c);
if(ff->ch[cc]==f) ff->setc(cur,cc);
else cur->fa=ff;
f->pushup();
}
void splay(node *cur,node *tar)
{
while(cur->fa!=tar)
{
if(cur->fa->fa==tar) rotate(cur);
else
{
if(cur->getd()==cur->fa->getd()) rotate(cur->fa);
else rotate(cur);
rotate(cur);
}
}
cur->pushup();
}
node *getpre(node *cur)
{
cur=cur->ch[0];
while(cur->ch[1]!=null) cur=cur->ch[1];
return cur;
}
node *getnext(node *cur)
{
cur=cur->ch[1];
while(cur->ch[0]!=null) cur=cur->ch[0];
return cur;
}
ll getabs(ll val)
{
if(val>0) return val;
else return -val;
}
int main()
{
node *pre,*nxt;
ll ans,minn;
int i;
scanf("%d",&n);
for(i=1;i<=n;i++) scanf("%lld",&ary[i]);
init();
for(i=1;i<=n;i++)
{
mp[i]=insert(root->ch[1]->ch[0],root->ch[1],ary[i]);
splay(mp[i],root->ch[1]);
if(i==1) ans=ary[i];
else
{
pre=getpre(mp[i]);
nxt=getnext(mp[i]);
minn=N;
if(pre!=null) minn=min(minn,getabs(pre->val-ary[i]));
if(nxt!=null) minn=min(minn,getabs(nxt->val-ary[i]));
ans+=minn;
}
}
printf("%lld\n",ans);
return 0;
}