0pts 无旋平衡树求助
查看原帖
0pts 无旋平衡树求助
663195
Z_AuTwT楼主2024/6/25 18:07
#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){
		x=Root;
		spilt(tr[Root].R,Value,tr[Root].R,y);
	}else{
		y=Root;
		spilt(tr[Root].L,Value,x,tr[Root].L);
	}
	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_rk(int &root,int Value){
	spilt(root,Value-1,X,Y);
	int res=tr[X].Size+1;
	root=merge(X,Y);
	return res;
}
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(){
	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]);
			}else{
				dfs(ROOT[tr[Y].id],ROOT[tr[X].id]);
			}
		}
	}
	cin>>q;
	while(q--){
		char op;
		cin>>op;
		int xx=read(),yy=read();
		if(op=='Q'){
			xx=find(xx);
			if(tr[ROOT[xx]].Size<yy) puts("-1");
			else{
				cout<<Get_rk(ROOT[xx],yy)<<"\n";
			}
		}else{
			xx=find(xx);
			yy=find(yy);
			if(xx==yy) continue;
			if(tr[ROOT[xx]].Size<tr[ROOT[yy]].Size){
				fa[xx]=yy;
				dfs(ROOT[xx],ROOT[yy]);
			}else{
				fa[yy]=xx;
				dfs(ROOT[yy],ROOT[xx]);
			}
		}
	}
}
2024/6/25 18:07
加载中...