https://www.lydsy.com/JudgeOnline/problem.php?id=2733
https://www.luogu.org/problemnew/show/P3224
C++版本一
题解:线段树+并查集+线段树合并
用并查集维护连通性,每个连通块内建一棵权值线段树,操作只有合并俩线段树以及查询排名
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
#define endl "\n"
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100000+10;
const int M=2000000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,p,l,r,q,sz;
int ans,cnt,flag,temp;
int v[N],id[N],fa[N],root[N];
int ls[M],rs[M],sum[M];
int find(int x){
return x==fa[x]?x:fa[x]=find(fa[x]);
}
void insert(int &k,int l,int r,int val){
if(!k)k=++sz;
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]];
}
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]]);
}
int merge(int x,int y){
if(!x)return y;
if(!y)return x;
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()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
//scanf("%d",&t);
//while(t--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&v[i]);
}
for(int i=1;i<=n;i++)fa[i]=i;
int x,y;
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
int tx=find(x);
int ty=find(y);
fa[tx]=ty;
}
for(int i=1;i<=n;i++){
insert(root[find(i)],1,n,v[i]);
id[v[i]]=i;
}
scanf("%d",&q);char ch[2];
while(q--){
scanf("%s",ch);
scanf("%d%d",&x,&y);
if(ch[0]=='Q'){
int p=find(x);
if(sum[root[p]]<y){
puts("-1");continue;
}
int t=query(root[p],1,n,y);
printf("%d\n",id[t]);
}else {
int p=find(x),q=find(y);
if(p!=q){
fa[p]=q;
root[q]=merge(root[p],root[q]);
}
}
}
//}
#ifdef DEBUG
printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
//cout << "Hello world!" << endl;
return 0;
}
C++版本二
题解:平衡树