( ext{Problem})
( ext{Solution})
学了线段树合并后发现它是个模板
它确实模板
于是我们只要维护若干棵权值线段树,询问直接找,连边合并就好
并查集维护一坨一坨的关系
注意并查集合并和线段树合并的方向一致即可
( ext{Code})
#include<cstdio>
using namespace std;
const int N = 1e5 + 5;
int n, m, q, size, fa[N], id[N], rt[N];
int sum[N * 32], ls[N * 32], rs[N * 32];
inline void pushup(int p){sum[p] = sum[ls[p]] + sum[rs[p]];}
void merge(int &x, int y)
{
if (!x || !y) return void(x += y);
merge(ls[x], ls[y]);
merge(rs[x], rs[y]);
pushup(x);
}
int find(int x){return (fa[x] == x ? x : fa[x] = find(fa[x]));}
inline void dsu_union(int x, int y)
{
int u = find(x), v = find(y);
if (u == v) return;
fa[v] = fa[u];
merge(rt[u], rt[v]);
rt[v] = 0;
}
void update(int &p, int l, int r, int x)
{
if (!p) p = ++size;
if (l == r) return void(++sum[p]);
int mid = (l + r) >> 1;
if (x <= mid) update(ls[p], l, mid, x);
else update(rs[p], mid + 1, r, x);
pushup(p);
}
int query(int p, int l, int r, int x)
{
if (sum[p] < x) return -1;
if (l == r) return id[l];
int mid = (l + r) >> 1;
if (sum[ls[p]] >= x) return query(ls[p], l, mid, x);
return query(rs[p], mid + 1, r, x - sum[ls[p]]);
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1, x; i <= n; i++)
fa[i] = i, scanf("%d", &x), id[x] = i, update(rt[i], 1, n, x);
for(int i = 1, x, y; i <= m; i++)
scanf("%d%d", &x, &y), dsu_union(x, y);
scanf("%d", &q);
char op[5];
for(int i = 1, x, y; i <= q; i++)
{
scanf("%s%d%d", op, &x, &y);
if (op[0] == 'Q') printf("%d
", query(rt[find(x)], 1, n, y));
else dsu_union(x, y);
}
}