0pts 无旋平衡树求助
查看原帖
0pts 无旋平衡树求助
663195
Z_AuTwT楼主2024/6/26 08:16
#include<bits/stdc++.h>
using namespace std;
inline int read(){
	char ch=getchar();
	int res=0,f=1;
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())res=(res<<3)+(res<<1)+(ch-'0');
	return res*f;
}
void write(int x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
    return;
}
int cnt,ROOT[100010],X,Y,Z;
struct Tree{
	int L,R,Size=0,Key,value,id,Cnt;
}tr[100010];
void update(int k){
	tr[k].Size=tr[tr[k].L].Size+tr[tr[k].R].Size+1;
}
void spilt(int Root,int Value,int &x,int &y){
	if(!Root){
		x=y=0;
		return;
	}
	if(tr[Root].value<=Value){
		y=Root;
		spilt(tr[Root].L,Value,x,tr[Root].L);
		
	}else{
		x=Root;
		spilt(tr[Root].R,Value,tr[Root].R,y);
	}
	update(Root);
}
int merge(int x,int y){
	if(!x||!y) return x+y;
	if(tr[x].Key>tr[y].Key){
		tr[x].R=merge(tr[x].R,y);
		update(x);
		return x;
	}else{
		tr[y].L=merge(x,tr[y].L);
		update(y);
		return y;
	}
}
int New(int root,int Value){
	cnt++;
	tr[cnt].value=Value;
	tr[cnt].Size=1;
	tr[cnt].id=root;
	tr[cnt].Key=rand();
	tr[cnt].L=tr[cnt].R=0;
	tr[cnt].Cnt=cnt;
	return cnt;
}
void Insert(int &root,int Value,int ID){
	Z=ID;
	spilt(root,Value,X,Y);
	root=merge(merge(X,Z),Y);
}
int Get_value(int root,int rk){
	int RT=root;
	while(RT){
		if(tr[tr[RT].L].Size+1==rk){
			break;
		}
		if(tr[tr[RT].L].Size>=rk){
			RT=tr[RT].L;
		}else{
			rk-=(tr[tr[RT].L].Size+1);
			RT=tr[RT].R;
		}
	}
	return tr[RT].id;
}
int fa[100010],P[100010];
int n,m,q;
int find(int x){
	if(x==fa[x]) return x;
	return fa[x]=find(fa[x]);
}
void dfs(int XX,int &YY){
	if(!XX) return;
	dfs(tr[XX].L,YY);
	dfs(tr[XX].R,YY);
	tr[XX].L=tr[XX].R=0;
	tr[XX].Size=1;
	Insert(YY,tr[XX].value,tr[XX].Cnt);
	return;
}
int main(){
    srand(int(time(0)));
	n=read(),m=read();
	for(int i=1;i<=n;i++){
		P[i]=read();
		fa[i]=i;
		ROOT[i]=New(i,P[i]);
	}
	for(int i=1;i<=m;i++){
		int u,v;
		cin>>u>>v;
		int X=find(u),Y=find(v);
		if(X!=Y){
			int x=tr[ROOT[tr[X].id]].Size,y=tr[ROOT[tr[Y].id]].Size;
			if(x<y){
				dfs(ROOT[tr[X].id],ROOT[tr[Y].id]);
				fa[X]=Y;
			}else{
				dfs(ROOT[tr[Y].id],ROOT[tr[X].id]);
				fa[Y]=X;
			}
		}
	}
	cin>>q;
	while(q--){
		char op;
		cin>>op;
		int xx=read(),yy=read();
		if(op=='Q'){
			xx=find(xx);
			if(tr[ROOT[tr[xx].id]].Size<yy) puts("-1");
			else{
				cout<<Get_value(ROOT[tr[xx].id],yy)<<"\n";
			}
		}else{
			xx=find(xx);
			yy=find(yy);
			if(xx==yy) continue;
			if(tr[ROOT[tr[xx].id]].Size<tr[ROOT[tr[yy].id]].Size){
				dfs(ROOT[tr[xx].id],ROOT[tr[yy].id]);
				fa[xx]=yy;
			}else{
				dfs(ROOT[tr[yy].id],ROOT[tr[xx].id]);
				fa[yy]=xx;
			}
		}
	}
}
2024/6/26 08:16
加载中...