import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{ public int x,seat; public String S, l;
Codechef()
{
this.x=0;
this.S="";
this.l="";
this.seat=0;
}
public static void main (String[] args)
{ Scanner s=new Scanner(System.in);
int t=s.nextInt();
int T=1,N,Q;
while(T<=t)
{
N=s.nextInt();
Q=s.nextInt();
int a[]=new int[Q];int b[]=new int[Q];
Codechef c[]=new Codechef[N3];
for(int i=0
;i<N3;i++)
{c[i]=new Codechef();}
int[] p=new int[N*3];
String[] q=new String[N*3];
String[] r=new String[N*3];
for(int i=0;i<N*3;i++)
{ p[i]=s.nextInt();
c[i].x=p[i];
q[i]=s.next();
c[i].S=q[i];
r[i]=s.next();
c[i].l=r[i];
}
for(int i=0;i<Q;i++)
{
a[i]=s.nextInt();
b[i]=s.nextInt();
}
for(int i=0;i<N*3;i++)
{if(c[i].l.equalsIgnoreCase("y")==true)
{
c[i].seat=1;
}
else{
for(int j=0;j<N*3;j++)
{
if(i!=j)
{
if( c[i].x==c[j].x)
{
if(c[j].l.equalsIgnoreCase("y")==false)
{ if((c[i].S.compareTo(c[j].S))>0)
{
c[i].seat=3 ; }
else
{ c[i].seat=2 ;
}
}
}
}
}
}
}
for(int f=0;f<Q;f++)
{
for(int j=0;j<N*3;j++)
{ if(a[f]==c[j].x && b[f]==c[j].seat)
{System.out.println(c[j].S);
}}
}
T++;
}
}
}