#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int T,i,N,M,j,k,t;
int flag =0;
scanf("%d",&T);
char ***results= new char **[T];
int * num = new int [T];
for(i=0;i<T;i++)
{
scanf("%d",&N);
N=N-1;
scanf("%d",&M);
M=M*2;
char **wordlist =new char *[M];
for(j=0;j<M;j++)
{
wordlist[j]=new char[23];
scanf("%s",wordlist[j]);
}
char **sencetence = new char *[100];
results[i] = new char *[100];
getchar();
char p[2000];
gets(p);
num[i]=0;
char *tokenPtr=strtok(p," ");
while(tokenPtr!=NULL)
{
sencetence[num[i]] = new char [23];
strcpy(sencetence[num[i]],tokenPtr);
num[i]++;
tokenPtr=strtok(NULL," ");
}
for(j =0;j<num[i];j++)
{
flag =0;
results[i][j] = new char[23];
for(k = 0;k<M;k=k+2){
if(strcmp(sencetence[j],wordlist[k])==0)
{strcpy (results[i][j],wordlist[k+1]);
flag=1;
break;}
}
if(flag==0)
{strcpy(results[i][j],sencetence[j]);
continue;
}
for(t=0;t<N-1;t++){
for(k = 0;k<M;k=k+2){
if(strcmp(results[i][j],wordlist[k])==0)
{strcpy (results[i][j],wordlist[k+1]);
break;}
}
}
}
free(sencetence);
free(wordlist);
}
for(i =0;i<T;i++){
printf("Case #%d: ",i+1);
for(j=0;j<num[i];j++){
if(j<num[i]-1)
printf("%s ",results[i][j]);
else
printf("%s\n",results[i][j]);
}
}
free(results);
return 0;
}