SPLAY 排序模板

#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
struct node{
	int v,s,f,ch[2]; //ch[0]:left;ch[1]:right;
}a[maxn];
int root=1;
void out(int rt){
	if(rt){out(a[rt].ch[0]);  printf("%d ",a[rt].v);  out(a[rt].ch[1]);}
}
void rotate(int x,int op){
	int y=a[x].f,	z=a[y].f,	B=a[x].ch[op];
	a[x].ch[op]=y;	a[y].f=x;
	a[y].ch[!op]=B;	a[B].f=y;
	if(a[z].ch[0]==y)a[z].ch[0]=x;
	else	a[z].ch[1]=x;
	a[x].f=z;
}
void splay(int x){
	while(a[x].f){
		if(!a[a[x].f].f){
			rotate(x,x==a[a[x].f].ch[0]);		
		}else{
			int y=a[x].f,	z=a[y].f;
			int op=y==a[z].ch[0];
			if(a[y].ch[op] != x){
				rotate(y,op);	rotate(x,op);
			}else{
				rotate(x,!op);	rotate(x,op);
			}		
		}
	}
	root=x;
}
void insert(int rt,int x){
	int p=a[x].v>a[rt].v;
	if(!a[rt].ch[p]){
		a[rt].ch[p]=x;	a[x].f=rt;	splay(x);
	}else insert(a[rt].ch[p],x);
}
int main(){
	int n,x;
	cin>>n;	cin>>a[1].v;
	for(int i=2;i<=n;i++){
		scanf("%d",&a[i].v);
		insert(root,i);
	}
	out(root);
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值