
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
int maxsize,op,k,id=1,idx;
queue<int> history;
int dvis[10000001];
int main(){
scanf("%d",&maxsize);
while(cin>>op){
if(op==0) return 0;
if(op==1){
history.push(id);
id++;
dvis[id]=id;
idx=id;
if(int(history.size())>maxsize){
dvis[history.front()]=0;
history.pop();
id--;
}
}
if(op==2){
scanf("%d",&k);
if(idx+k-1>(int)history.size()){
puts("Error: no forward history");
}
printf("%d\n",dvis[idx+k-1]);
idx=k;
}
if(op==3){
scanf("%d",&k);
if(idx-k+1<1){
puts("Error: no back history");
}
printf("%d\n",dvis[idx-k+1]);
idx=k;
}
}
return 0;
}

