#include<bits/stdc++.h>
using namespace std;
struct Stu{
string Nam;
int tp;
int cd[3][2];
Stu(){}
Stu(string s,int *A,int *B,int *C){
Nam=s;tp=0;
cd[0][0]=A[0],cd[0][1]=A[1];
cd[1][0]=B[0],cd[1][1]=B[1];
cd[2][0]=C[0],cd[2][1]=C[1];
//baozi
if(cd[0][1]==cd[1][1]&&cd[1][1]==cd[2][1])tp=5;
//shunzi
else if((cd[0][1]+1==cd[1][1]&&cd[1][1]+1==cd[2][1])||(cd[0][1]==2&&cd[1][1]==3&&cd[2][1]==14)){
tp=2<<(cd[0][0]==cd[1][0]&&cd[1][0]==cd[2][0]);
if(cd[0][1]==2&&cd[1][1]==3&&cd[2][1]==14)cd[0][1]=1,cd[1][1]=2,cd[2][1]=3;
}
//jinhua
else if(cd[0][0]==cd[1][0]&&cd[1][0]==cd[2][0])tp=3;
//duizi
else if(cd[0][1]==cd[1][1]||cd[1][1]==cd[2][1])tp=1;
//dan
else tp=0;
}
bool operator <(const Stu &A)const{
if(tp^A.tp)return tp>A.tp;
if(tp==5||tp==3||tp==1||tp==0){
if(tp!=1){
bool flag=0;
for(int i=2;~i;i--)if(cd[i][1]!=A.cd[i][1])return cd[i][1]>A.cd[i][1];
return Nam>A.Nam;
}
if(cd[1][1]!=A.cd[1][1])return cd[1][1]>A.cd[1][1];
int a=((cd[0][1]==cd[1][1])?(cd[2][1]):(cd[0][1])),
b=((A.cd[0][1]==A.cd[1][1])?(A.cd[2][1]):(A.cd[0][1]));
return (a==b)?Nam>A.Nam:a>b;
}
return (cd[0][0]==A.cd[0][0])?Nam>A.Nam:cd[0][0]>A.cd[0][0];
}
}s[103];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
string Nam;
int cd[3][2];
for(int i=1;i<=n;i++){
cin>>Nam;
for(int j=0;j<3;j++){
char ch;
scanf(" %c",&ch);
cd[j][0]=ch-'a';
ch=getchar();
if(ch=='1')getchar(),cd[j][1]=10;
else if(ch=='J')cd[j][1]=11;
else if(ch=='Q')cd[j][1]=12;
else if(ch=='K')cd[j][1]=13;
else if(ch=='A')cd[j][1]=14;
else cd[j][1]=ch-'0';
}
//sort
if(cd[0][1]>cd[1][1])swap(cd[0],cd[1]);
if(cd[0][1]>cd[2][1])swap(cd[0],cd[2]);
if(cd[1][1]>cd[2][1])swap(cd[1],cd[2]);
s[i]=Stu(Nam,cd[0],cd[1],cd[2]);
//Print
// printf("Stu %d\n",i);
// cout<<"Nam "<<s[i].Nam<<endl;
// cout<<s[i].tp<<endl;
// cout<<s[i].cd[0][0]<<" "<<s[i].cd[0][1]<<endl;
// cout<<s[i].cd[1][0]<<" "<<s[i].cd[1][1]<<endl;
// cout<<s[i].cd[2][0]<<" "<<s[i].cd[2][1]<<endl;
}
sort(s+1,s+1+n);
for(int i=1;i<=n;i++)cout<<s[i].Nam<<endl;
}
return 0;
}