#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 0;
cin >> n;
stack<int>arr;
stack<int>brr;
long long int xrr[150001];
long long int crr[150001];
char temp;
int tp;
int t = 0;
while (n--)
{
cin >> temp;
if (temp == 'I')
{
cin >> tp;
arr.push(tp);
if (t == 0)
{
xrr[++t] = tp;
crr[t] = tp;
}
else
{
xrr[++t] = xrr[t - 1] + tp;
crr[t] = max(crr[t - 1], xrr[t]);
}
}
else if (temp == 'D')
{
if (!arr.empty())
{
arr.pop();
t--;
}
}
else if (temp == 'L')
{
if (!arr.empty())
{
tp = arr.top();
arr.pop();
brr.push(tp);
t--;
}
}
else if (temp == 'R')
{
if (!brr.empty())
{
tp = brr.top();
brr.pop();
arr.push(tp);
xrr[++t] = xrr[t - 1] + tp;
crr[t] = max(crr[t - 1], xrr[t]);
}
}
else if (temp == 'Q')
{
cin >> tp;
cout << crr[tp] << endl;
}
}
}