# Bzoj2733 [hnoi2012]永无乡

## 权值线段树入门题

Posted by yjjr's blog on March 8, 2018 1 minutes to read

# 题目

## Sample Input

5  1
4  3 2 5 1
1  2
7
Q 3 2
Q 2 1
B 2 3
B 1 5
Q 2 1
Q 2 4
Q 2 3


## Sample Output

-1
2
5
1
2


# code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
using namespace std;
{
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=1e5+6,maxm=2e6+6;
int ls[maxm],rs[maxm],fa[maxn],sum[maxm],root[maxn],v[maxn],pos[maxn],id,n,m,T;
char ch[2];
inline int find(int x){return x==fa[x]?fa[x]:fa[x]=find(fa[x]);}
void insert(int &k,int l,int r,int val){
if(!k)k=++id;
if(l==r){sum[k]=1;return;}
int mid=(l+r)>>1;
if(val<=mid)insert(ls[k],l,mid,val);else insert(rs[k],mid+1,r,val);
sum[k]=sum[ls[k]]+sum[rs[k]];
}
inline int query(int k,int l,int r,int rank){
if(l==r)return l;
int mid=(l+r)>>1;
if(sum[ls[k]]>=rank)return query(ls[k],l,mid,rank);
else return query(rs[k],mid+1,r,rank-sum[ls[k]]);
}
inline int merge(int x,int y){
if(!x||!y)return x+y;
ls[x]=merge(ls[x],ls[y]);
rs[x]=merge(rs[x],rs[y]);
sum[x]=sum[ls[x]]+sum[rs[x]];
return x;
}
int main()
{
rep(i,1,n)fa[i]=i;
rep(i,1,m){
int root1=find(x),root2=find(y);
fa[root1]=root2;
}
rep(i,1,n){
insert(root[find(i)],1,n,v[i]);
pos[v[i]]=i;
}
while(T--){
scanf("%s",ch);
if(ch[0]=='Q'){
int root1=find(x);
if(sum[root[root1]]<y){puts("-1");continue;}
int tmp=query(root[root1],1,n,y);
printf("%d\n",pos[tmp]);
}else{
int root1=find(x),root2=find(y);
if(root1!=root2){
fa[root1]=root2;
root[root2]=merge(root[root1],root[root2]);
}
}
}
return 0;
}