#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, root, tot;
struct FHQ {
int l, r;
char val;
int key, size;
} t[N];
int New(char ch) {
tot++;
t[tot].l = t[tot].r = 0, t[tot].size = 1;
t[tot].val = ch, t[tot].key = rand();
return tot;
}
void update(int p) {
t[p].size = t[t[p].l].size + t[t[p].r].size + 1;
}
void split(int p, int k, int &l, int &r) {
if (p == 0) {
l = r = 0;
return;
}
if (t[t[p].l].size + 1 <= k) {
l = p;
split(t[p].r, k - t[t[p].l].size - 1, t[p].r, r);
}
else {
r = p;
split(t[p].l, k, l, t[p].l);
}
update(p);
}
int merge(int l, int r) {
if (l == 0 || r == 0) return l + r;
if (t[l].key > t[r].key) {
t[l].r = merge(t[l].r, r);
update(l);
return l;
}
else {
t[r].l = merge(l, t[r].l);
update(r);
return r;
}
}
void inorder(int p) {
if (p == 0) return;
inorder(t[p].l);
cout << t[p].val;
inorder(t[p].r);
}
int main() {
freopen("P4008_1.in", "r", stdin);
freopen("P4008.out", "w", stdout);
int len, pos = 0, p, L, R;
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
srand(time(NULL));
cin >> n;
while (n--) {
string opt;
cin >> opt;
if (opt[0] == 'M') cin >> pos;
if (opt[0] == 'I') {
cin >> len;
split(root, pos, L, R);
for (int i = 1; i <= len; i++) {
char ch = getchar();
while (ch < 32 || ch > 126) ch = getchar();
L = merge(L, New(ch));
}
root = merge(L, R);
}
if (opt[0] == 'D') {
cin >> len;
split(root, pos + len, L, R);
split(L, pos, L, p);
root = merge(L, R);
}
if (opt[0] == 'G') {
cin >> len;
split(root, pos + len, L, R);
split(L, pos, L, p);
inorder(p);
cout << endl;
root = merge(merge(L, p), R);
}
if (opt[0] == 'P') pos--;
if (opt[0] == 'N') pos++;
}
return 0;
}