权值线段树+线段树合并+并查集TLE求调
查看原帖
权值线段树+线段树合并+并查集TLE求调
554470
Planetary_system楼主2023/12/18 12:47

#2 #7 #8 #9 #10 TLE\text{TLE}

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e9+10;
struct node{int l,r,sum;}tree[4000000];
int tot,n,m,q,f[200000],p[200000],root[200000],id[200000];
vector<int>g[200000];
int find(int x){
	return f[x]=(x==f[x]?x:find(f[x]));
}
void push_up(int p){
	int ls=tree[p].l,rs=tree[p].r;
	tree[p].sum=tree[ls].sum+tree[rs].sum;
	return;
}
void modify(int &p,int l,int r,int x,int v,int d){
	if(p==0)p=++tot;
	if(l==r){
		tree[p].sum+=v;
		id[p]=d;
		return;
	}
	int mid=l+r>>1;
	if(x<=mid)modify(tree[p].l,l,mid,x,v,d);
	else modify(tree[p].r,mid+1,r,x,v,d);
	push_up(p);
	return;
}
int merge(int a,int b,int l,int r){
	if(a==0)return b;
	if(b==0)return a;
	if(l==r){
		if(id[b])id[a]=id[b];
		tree[a].sum+=tree[b].sum;
		return a;
	}
	int mid=l+r>>1;
	tree[a].l=merge(tree[a].l,tree[b].l,l,mid);
	tree[a].r=merge(tree[a].r,tree[b].r,mid+1,r);
	push_up(a);
	return a;
}
int query(int p,int k,int x,int y){
	if(x==y)return id[p];
	int mid=(x+y)>>1;
	int ans;
	if(k<=tree[tree[p].l].sum)ans=query(tree[p].l,k,x,mid);
	else ans=query(tree[p].r,k-tree[tree[p].l].sum,mid+1,y);
	return ans;
}
signed main(){
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=n;i++)
		f[i]=i;
	for(int i=1;i<=n;i++){
		scanf("%lld",&p[i]);
		modify(root[i],1,n,p[i],1,i);
	}
	for(int i=1,u,v;i<=m;i++){
		scanf("%lld%lld",&u,&v);
		if(find(u)!=find(v)){
			root[find(u)]=merge(root[find(u)],root[find(v)],1,n);
			f[find(v)]=find(u);
		}
	}
	scanf("%lld",&q);
	while(q--){
		char op;
		int u,v;
		scanf(" %c%lld%lld",&op,&u,&v);
		if(op=='B'){
			if(find(u)!=find(v)){
				root[find(u)]=merge(root[find(u)],root[find(v)],1,n);
				f[find(v)]=find(u);
			}
		}
		else if(tree[root[find(u)]].sum<v)printf("-1\n");
		else printf("%lld\n",query(root[find(u)],v,1,n));
	}
	return 0;
}
2023/12/18 12:47
加载中...