1. 

/**
* ACM
* UVa Status: accepted
* Run Time: 0.040
* Category: ad hoc
* @author Evgeni Pavlidis evgenipavlidis@yahoo.de
*/
#include <iostream>

#define DEBUG 0
#define NaN -1

using namespace std;

static int ref[25];
static int n;

int getTail(int a, bool print)
{
if(print)
cout << a;

for(int i=0; i<n; i++)
if(ref[i] == a)
{
if(print)
cout << " ";
return getTail(i,print);
}

return a;
}


void printResults()
{
for(int i=0; i<n; i++)
{
cout << i << ":";
if(ref[i] == NaN)
{
cout << " ";
getTail(i,true);
}
cout << endl;
}
}


void removeTail(int a)
{
for(int i=0; i<n; i++)
if(ref[i] == a)
{
removeTail(i);
ref[i] = NaN;
}
}

bool onSameStack(int j, int b)
{
while(ref[j] != NaN)
if(ref[j] == b)
return true;
else
j = ref[j];

return false;
}

int main()
{
for(int i=0; i < 25; i++)
ref[i] = NaN;

cin >> n;

string command,mode;
int a,b;

while(true)
{
cin >> command;
if(command == "quit")
{
printResults();
return 0;
}

cin >> a;
cin >> mode;
cin >> b;

if(a == b || onSameStack(a,b) || onSameStack(b,a))
continue;

if(mode == "onto")
removeTail(b);

if(command == "move")
removeTail(a);

ref[a] = getTail(b,false);

if(DEBUG)
printResults();
}
}