1 #include <cstdio>
2 #define mx 200000
3 int n, m, a, b, bk[mx], id[mx];
4 char str[10];
5 int f[mx], c[mx][2], s[mx], k[mx], size, root;
6
7 inline void pushup (int x)
8 {
9 s[x] = s[c[x][0]] + s[c[x][1]] + 1;
10 }
11
12 inline int rotate (int i)
13 {
14 int fa = f[i], d = (c[fa][1] == i);
15 f[i] = f[fa], fa > 0 ? c[f[fa]][c[f[fa]][1] == fa] = i : 0;
16 (c[fa][d] = c[i][!d]) ? f[c[i][!d]] = fa : 0;
17 pushup (c[f[fa] = i][!d] = fa);
18 return i;
19 }
20
21 inline void splay (int i, int p)
22 {
23 for (int fa = f[i]; fa != p; fa = f[rotate (i)])
24 f[fa] != p ? rotate (c[fa][1] == i ^ c[f[fa]][1] == fa ? i : fa): 0;
25 pushup (i);
26 if (f[i] == 0) root = i;
27 }
28
29 int build (int fa, int l, int r)
30 {
31 if (l > r) return 0;
32 int m = (l + r) >> 1;
33 int i = ++size;
34 f[i] = fa;
35 k[i] = bk[m];
36 id[bk[m]] = i;
37 c[i][0] = build (i, l, m - 1);
38 c[i][1] = build (i, m + 1, r);
39 pushup (i);
40 return i;
41 }
42
43 int check (int t, int i)
44 {
45 if (c[i][t] == 0) return i;
46 return check (t, c[i][t]);
47 }
48
49 int ask (int i, int key)
50 {
51 int t = s[c[i][0]];
52 if (key <= t) return ask (c[i][0], key);
53 if (key > t + 1) return ask (c[i][1], key - t - 1);
54 return k[i];
55 }
56
57 void exchange (int t, int i)
58 {
59 splay (i, 0);
60 if (c[i][t] == 0) return;
61 int x = check (!t, c[i][t]);
62 k[i] ^= k[x];
63 k[x] ^= k[i];
64 k[i] ^= k[x]; // swap
65 id[k[i]] = i;
66 id[k[x]] = x;
67 }
68
69 void move (int t, int i)
70 {
71 splay (i, 0);
72 if (c[i][1] > 0)
73 {
74 int x = check (0, c[i][1]);
75 splay (x, i);
76 c[x][0] = c[i][0];
77 f[c[x][0]] = x;
78 pushup (x);
79 root = x;
80 }else
81 {
82 f[c[i][0]] = 0;
83 root = c[i][0];
84 }
85 f[i] = c[i][0] = c[i][1] = 0;
86 f[root] = i;
87 c[i][t] = 0;
88 c[i][!t] = root;
89 pushup (i);
90 root = i;
91 splay (i, 0);
92 }
93
94 int main ()
95 {
96 scanf ("%d %d", &n, &m);
97 for (int i = 1; i <= n; i++)
98 scanf ("%d", &bk[i]);
99 root = build (0, 1, n);
100 for (int i = 0; i < m; i++)
101 {
102 scanf ("%s %d", str, &a);
103 switch (str[0])
104 {
105 case ‘T‘:
106 move (0, id[a]);
107 break;
108 case ‘B‘:
109 move (1, id[a]);
110 break;
111 case ‘I‘:
112 scanf ("%d", &b);
113 if (b != 0) exchange (b == 1, id[a]);
114 break;
115 case ‘A‘:
116 splay (id[a], 0);
117 printf ("%d\n", s[c[id[a]][0]]);
118 break;
119 case ‘Q‘:
120 printf ("%d\n", ask (root, a));
121 break;
122 }
123 }
124 }