/*

Pamatuji si pozici vsech auticek, tim moc neusetrim, ale je to podle me dobry napad

Zase zadna mezera na konci (pisou mezi a ne za kazdym)

co to stopovat sekvenci "stop"? to neni legalni retezec vstupu

obraceni retezce by slo i lip...
*/


#include<stdio.h>
#include<string.h>

#define STOP "STOP"

int main(void)
{
  int set=1, end, start, i, n, pos;
  char buf[256];
  char tmp[256];
  int howm, where;
  char *garage;
  char a;
  int autos[32];
  gets( buf );
  while( strcmp( buf, STOP ) )
    {
      if( set>1 ) putchar( '\n' );
      printf( "Dataset #%d:  The initial order is %s.\n", set, buf ); 
      garage=buf;
      start=0;
      for( end=0; garage[end]; ++end ) autos[garage[end]-'A']=end;
      scanf( "%d\n", &n );
      while( n-- )
	{
	  scanf( "%c\n", &a );
	  pos=autos[a-'A']; 
	  if( pos-start < end-pos )
	    {
	      howm=pos-start;
	      strncpy( tmp, garage, howm );
	      ++garage;
	      where=++start;
	    }
	  else
	    {	 
	      --end;
	      howm=end-pos;
	      where=pos;
	      strncpy( tmp, buf+pos+1, howm );
	      buf[end]=0;
	    }
	  for( i=0; i<howm; ++i )
	    {
	      buf[where+i]=tmp[howm-1-i];
	      autos[tmp[howm-i-1]-'A']=where+i;
	    }
	  printf( "After %c leaves, the order is %s.\n", a, garage );
	}
      ++set;
      gets(buf);
    }
  return 0;
}