#include<bits/stdc++.h>
using namespace std;
list<int>l[1000010];
char s[20];
int main()
{
int q;
scanf("%d",&q);
while(q--)
{
scanf("%s",s);
if(strcmp(s,"pop_back")==0)
{
int x;
scanf("%d",&x);
if(!l[x].empty())
{
l[x].pop_back();
}
}
if(strcmp(s,"push_back")==0)
{
int x,y;
scanf("%d%d",&x,&y);
l[x].push_back(y);
}
if(strcmp(s,"push_front")==0)
{
int x,y;
scanf("%d%d",&x,&y);
l[x].push_front(y);
}
if(strcmp(s,"pop_front")==0)
{
int x;
scanf("%d",&x);
if(!l[x].empty())
{
l[x].pop_front();
}
}
if(strcmp(s,"size")==0)
{
int x;
scanf("%d",&x);
printf("%d\n",l[x].size());
}
if(strcmp(s,"front")==0)
{
int x;
scanf("%d",&x);
printf("%d\n",l[x].front());
}
if(strcmp(s,"back")==0)
{
int x;
scanf("%d",&x);
printf("%d\n",l[x].back());
}
}
return 0;
}