1 #include <bits/stdc++.h>
2 using namespace std;
3 struct spaly
4 {
5 int c[2], fa, siz, val;
6 int& operator[] (int x)
7 {
8 return c[x];
9 }
10 }a[100005];
11 int root[100005], fa[100005], sta[100005], top;
12
13 int getfa(int x)
14 {
15 return fa[x] = x == fa[x] ? x : getfa(fa[x]);
16 }
17
18 void LDR(int u)
19 {
20 if(!u) return;
21 LDR(a[u][0]), sta[++top] = u, LDR(a[u][1]);
22 }
23
24 void rotate(int &k, int x)
25 {
26 int y = a[x].fa, z = a[y].fa, dy = a[y][1] == x;
27 if(k == y) k = x;
28 else a[z][a[z][1] == y] = x;
29 a[y][dy] = a[x][!dy], a[a[x][!dy]].fa = y;
30 a[x][!dy] = y, a[y].fa = x, a[x].fa = z;
31 a[y].siz = a[a[y][0]].siz + a[a[y][1]].siz + 1;
32 }
33
34 void splay(int &k, int x)
35 {
36 while(k != x)
37 {
38 int y = a[x].fa, z = a[y].fa;
39 if(k != y)
40 if(a[y][1] == x ^ a[z][1] == y) rotate(k, x);
41 else rotate(k, y);
42 rotate(k, x);
43 }
44 a[x].siz = a[a[x][0]].siz + a[a[x][1]].siz + 1;
45 }
46
47 void insert(int &k, int x)
48 {
49 if(!k)
50 {
51 k = x, a[x].siz = 1, a[x][0] = a[x][1] = 0;
52 return;
53 }
54 ++a[k].siz;
55 if(a[x].val < a[k].val)
56 insert(a[k][0], x), a[a[k][0]].fa = k;
57 else insert(a[k][1], x), a[a[k][1]].fa = k;
58 }
59
60 int find_kth(int k, int x)
61 {
62 if(!k) return -1;
63 if(x <= a[a[k][0]].siz) return find_kth(a[k][0], x);
64 if(x == a[a[k][0]].siz + 1) return k;
65 return find_kth(a[k][1], x - a[a[k][0]].siz - 1);
66 }
67
68 void addedge(int u, int v)
69 {
70 if(u == v) return;
71 if(a[root[u]].siz < a[root[v]].siz)
72 swap(u, v);
73 fa[v] = u, LDR(root[v]);
74 while(top)
75 {
76 insert(root[u], sta[top]);
77 splay(root[u], sta[top--]);
78 }
79 }
80
81 int main()
82 {
83 int n, m, q, u, v;
84 char op[5];
85 scanf("%d%d", &n, &m);
86 for(int i = 1; i <= n; ++i)
87 scanf("%d", &a[i].val);
88 for(int i = 1; i <= n; ++i)
89 root[i] = fa[i] = i, a[i].siz = 1;
90 while(m--)
91 {
92 scanf("%d%d", &u, &v);
93 addedge(getfa(u), getfa(v));
94 }
95 scanf("%d", &q);
96 while(q--)
97 {
98 scanf("%s%d%d", op, &u, &v);
99 if(op[0] == ‘B‘) addedge(getfa(u), getfa(v));
100 else printf("%d\n", find_kth(root[getfa(u)], v));
101 }
102 return 0;
103 }