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