splay一直都调不出来
查看原帖
splay一直都调不出来
475329
Larryyu楼主2023/1/31 09:58

rt,

#include<bits/stdc++.h>
using namespace std;
int tr[40000][2];
int cnt[40000];
int siz[40000];
int fa[40000];
int val[40000];
int rt,tot;
int n,sum;
bool check(int x){
	return x==tr[fa[x]][1];
}
void upd(int x){
	siz[x]=siz[tr[x][0]]+siz[tr[x][1]]+cnt[x];
}
void rotate(int x){
	int y=fa[x];
	int z=fa[y];
	int tp=check(x);
	tr[y][tp]=tr[x][tp^1];
	fa[tr[x][tp^1]]=y;
	
	tr[x][tp^1]=y;
	fa[x]=z;
	if(z) tr[z][check(y)]=x;
	fa[y]=x;
	upd(y);
	upd(x);
}
void splay(int x){
	int fax=fa[x];
	while(fax){
		if(fa[fax]){
			if(check(fax)==check(x)){
				rotate(fax);
			}else rotate(x); 
		}
		rotate(x);
		fax=fa[x];
	}
	rt=x;
	
	
}
void insert(int x){
	if(rt==0){
		val[++tot]=x;
		cnt[tot]++;
		rt=tot;
		upd(tot);
		 
		return;
	}
	int fax=0;
	int now=rt;
	while(1){
		if(val[now]==x){
			cnt[now]++;
			upd(now);
			if(fax!=0) upd(fax);
			
			splay(now);
			return;
		}
		fax=now;
		now=tr[now][x>val[now]];
		if(now==0){
			val[++tot]=x;
			cnt[tot]++;
			
			tr[fax][x>val[fax]]=tot;
			fa[tot]=fax;
			upd(tot);
			splay(tot);
			return;
		}
	}
}
int pre(int x){
	int now=tr[rt][x];
	while(tr[now][x^1]){
		now=tr[now][x^1];
	}
	splay(now);
	return now;
}
int main(){
	cin>>n;
	int zz;
	cin>>zz;
	insert(zz);
	sum=zz;
	for(int i=2;i<=n;i++){
		int x;
		cin>>x;
		insert(x);
		sum+=min(abs(x-val[pre(0)]),abs(x-val[pre(1)));
	}
	cout<<sum<<endl;
	return 0;
}
2023/1/31 09:58
加载中...