一道经典的平衡树板子题。
我记得之前写这道题的题解的时候,写的是“查询根节点的前驱后继与它本身做差取最小”,但是这样的说法其实有一个问题。
“前驱”的定义是小于 x x x的最大值。
注意,在定义中是不能取等的,但是这道题根据题目的意思显然可以取等,也就是说,这道题要求的并不是严格的“前驱”与“后继”。
所以我们在插入值之后,应该要先判断一下 c n t [ r o o t ] cnt[root] cnt[root]的值,然后再考虑是否去求前驱与后继。
#include<cstdio>
const int N=1e5+5;
const int inf=1e9;
int n,ans,rt,tot,fa[N],ch[N][2],val[N],cnt[N],sz[N];
struct Splay {
void maintain(int x) {
sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+cnt[x];
}
bool get(int x) {
return x==ch[fa[x]][1];
}
void clear(int x) {
ch[x][0]=ch[x][1]=fa[x]=val[x]=sz[x]=cnt[x]=0;
}
void rotate(int x) {
int y=fa[x],z=fa[y],chk=get(x);
ch[y][chk]=ch[x][chk^1]; fa[ch[x][chk^1]]=y; ch[x][chk^1]=y;
fa[y]=x; fa[x]=z;
if(z) ch[z][y==ch[z][1]]=x;
maintain(x); maintain(y);
}
void splay(int x) {
for(int f=fa[x];f=fa[x],f;rotate(x))
if(fa[f]) rotate(get(x)==get(f)?f:x);
rt=x;
}
void ins(int k) {
if(!rt) {
val[++tot]=k;
cnt[tot]++;
rt=tot;
maintain(rt);
return;
}
int cnr=rt,f=0;
while(1) {
if(val[cnr]==k) {
cnt[cnr]++;
maintain(cnr); maintain(f);
splay(cnr);
break;
}
f=cnr;
cnr=ch[cnr][val[cnr]<k];
if(!cnr) {
val[++tot]=k;
cnt[tot]++;
fa[tot]=f;
ch[f][val[f]<k]=tot;
maintain(tot); maintain(f);
splay(tot);
break;
}
}
}
int pre() {
int cnr=ch[rt][0];
if(!cnr) return inf;
while(ch[cnr][1]) cnr=ch[cnr][1];
return val[cnr];
}
int nxt() {
int cnr=ch[rt][1];
if(!cnr) return inf;
while(ch[cnr][0]) cnr=ch[cnr][0];
return val[cnr];
}
}Tree;
inline int abs(int x){return x>0?x:-x;}
inline int min(int x,int y){return x>y?y:x;}
int main() {
scanf("%d",&n);
for(int i=1;i<=n;i++) {
int x;
scanf("%d",&x);Tree.ins(x);
if(i==1) ans=x;
else if(cnt[rt]>1) continue;
else ans+=min(abs(x-Tree.pre()),abs(x-Tree.nxt()));
}
printf("%d",ans);
return 0;
}