#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Book
{
string title;
string author;
int status;//1在 0借 -1还
Book(string t,string a,int b)
{
title = t;author = a;status = b;
}
};
vector<Book>books;
bool cmp(const Book & a,const Book & b)
{
if(a.author == b.author)
return a.title<b.title;
else
return a.author<b.author;
}
int main()
{
string s;
while(getline(cin,s)&&s!="END")
{
int i = s.find("by",1);
string t = s.substr(0,i-1);
string au = s.substr(i+3,s.length()-i-3);
books.push_back(Book(t,au,1));
}
sort(books.begin(),books.end(),cmp);
string q,name;
while(getline(cin,q)&&q!="END")
{
if(q[0]=='B'||q[0]=='R')
{
name = q.substr(7,q.length()-7);
for(int i = 0;i<books.size();i++)
{
if(books[i].title == name)
{
if(q[0]=='B') books[i].status = 0;
else books[i].status = -1;
}
}
}
else
{
int i,j;
for(i = 0;i<books.size();i++)
{
if(books[i].status == -1)
{
for(j = i-1;j>=0;j--)
{
if(books[j].status == 1)
{
break;
}
}
if(books[j].status == 1)
{
cout<<"Put "<<books[i].title<<" after "<<books[j].title<<endl;
}
else
{
cout<<"Put "<<books[i].title<<" first"<<endl;
}
books[i].status = 1;
}
}
cout << "END" << endl;
}
}
return 0;
}
/**
"The Canterbury Tales" by Chaucer, G.
"Algorithms" by Sedgewick, R.
"The C Programming Language" by Kernighan, B. and Ritchie, D.
END
BORROW "Algorithms"
BORROW "The C Programming Language"
RETURN "Algorithms"
RETURN "The C Programming Language"
SHELVE
END
**/