1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <bits/stdc++.h> #define MAX_N 100000 #define mid ((s+t)>>1) using namespace std; template <class T> inline void read(T &x) { x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } int n, m, a[MAX_N+5], b[MAX_N+5]; int sz, rt[MAX_N+5], fa[MAX_N+5]; struct node {int ls, rs, val;} tr[MAX_N*20]; int getf(int x) {return fa[x] == x ? x : fa[x] = getf(fa[x]);} void modify(int &v, int s, int t, int p) { if (!v) v = ++sz; if (s == t) {tr[v].val++; return;} if (p <= mid) modify(tr[v].ls, s, mid, p); if (p >= mid+1) modify(tr[v].rs, mid+1, t, p); tr[v].val = tr[tr[v].ls].val+tr[tr[v].rs].val; } int query(int v, int s, int t, int k) { if (s == t) return s; int lsz = tr[tr[v].ls].val; if (lsz >= k) return query(tr[v].ls, s, mid, k); return query(tr[v].rs, mid+1, t, k-lsz); } int merge(int x, int y) { if (!x) return y; if (!y) return x; tr[x].ls = merge(tr[x].ls, tr[y].ls); tr[x].rs = merge(tr[x].rs, tr[y].rs); tr[x].val = tr[tr[x].ls].val+tr[tr[x].rs].val; return x; } int main() { read(n), read(m); for (int i = 1; i <= n; i++) read(a[i]), b[a[i]] = i, fa[i] = i; for (int i = 1, u, v; i <= m; i++) read(u), read(v), u = getf(u), v = getf(v), fa[v] = u; for (int i = 1; i <= n; i++) modify(rt[getf(i)], 1, n, a[i]); int T; read(T); while (T--) { char opt[2]; scanf("%s", opt); if (opt[0] == 'B') { int x, y; read(x), read(y), x = getf(x), y = getf(y); if (x^y) fa[y] = x, rt[x] = merge(rt[x], rt[y]); } else { int x, k; read(x), read(k); if (tr[rt[x = getf(x)]].val < k) puts("-1"); else printf("%d\n", b[query(rt[x], 1, n, k)]); } } return 0; }
|