Poj 2887 BigString

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include<bits/stdc++.h>
using namespace std;
const int MAXtxtlen = 1e6;
const int MAXsqrttxtlen = 1e3;

template <typename T>
inline void read(T &a) {
char c;for (c = getchar(); (c < '0' || c > '9') && c != '-'; c = getchar());bool f = c == '-';T x = f ? 0 : (c ^ '0');for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {x = x * 10 + (c ^ '0');}a = f ? -x : x;
}
template <typename T, typename ...Argv>
inline void read(T &a, Argv &...argv) {
read(a), read(argv...);
}

int n, sqrtn;
struct Node {
int len;
Node *pre, *nex;
char txt[MAXsqrttxtlen * 2 + 10];
Node() {len = 0, pre = nullptr, nex = nullptr, memset(txt, 0, sizeof(txt));}
inline void split(int p) {
Node *nw = new Node;
nw->nex = nex;
nex = nw;
nw->pre = this;
if (nw->nex != nullptr) nw->nex->pre = nw;
copy(txt + p + 1, txt + len + 1, nw->txt + 1);
nw->len = len - p;
len = p;
}
inline void insert(int p, char ch) {
for (int i = len; i > p; --i) {
txt[i + 1] = txt[i];
}
txt[p + 1] = ch;
++len;
if (len > sqrtn) {
split(len >> 1);
}
}
};
Node *head;
inline void Init(char *str) {
Node *last = nullptr;
for (int l = 1, r = sqrtn; ; l += sqrtn, r += sqrtn) {
Node *nw = new Node;
if (last != nullptr) {
nw->pre = last;
last->nex = nw;
} else {
head = nw;
}
nw->len = min(r, n) - l + 1;
copy(str + l, str + l + nw->len, nw->txt + 1);
last = nw;
if (r >= n) break;
}
}
inline char Query(int p) {
--p;
Node *cur = head;
while (p >= cur->len) {
p -= cur->len;
cur = cur->nex;
}
return cur->txt[1 + p];
}
inline void Insert(int p, char ch) {
--p;
Node *cur = head;
if (p == -1) {
cur->insert(0, ch);
return;
}
while (p >= cur->len) {
p -= cur->len;
cur = cur->nex;
}
cur->insert(1 + p, ch);
}

int m;
char str[MAXtxtlen + 10];
signed main() {
scanf("%s", str + 1);
n = strlen(str + 1);
sqrtn = sqrt(n);
Init(str);
read(m);
char opt, ch;
for (int i = 1, p; i <= m; ++i) {
scanf("%s", &opt);
if (opt == 'Q') {
read(p);
printf("%c\n", Query(p));
} else if (opt == 'I') {
scanf("%s", &ch);
read(p);
Insert(p - 1, ch);
} else {
puts("Error!");
exit(1);
}
}
return 0;
}