#include <bits/stdc++.h>
using namespace std;
const int N = 101;
string card[N][3];
int val[N][3];
struct node{
string nam;int val;
bool operator < (const node &a) const{
if(val != a.val) return val > a.val;
else return nam > a.nam;
}
}stu[N];
int n;
void work1(int x)
{
if(val[x][0] != val[x][1] || val[x][1] != val[x][2]) return;
stu[x].val = 60000000 + val[x][0];return;
}
void work2(int x)
{
if(card[x][0][0] != card[x][1][0] || card[x][1][0] != card[x][2][0]) return;
sort(val[x],val[x] + 3);
if(val[x][1] - val[x][0] == 1 && val[x][2] - val[x][1] == 1)
{ stu[x].val = 50000000 + val[x][0];return; }
if(val[x][0] == 2 && val[x][1] == 3 && val[x][2] == 14) { stu[x].val = 50000000 + 1;return;}
}
void work3(int x)
{
if(card[x][0][0] != card[x][1][0] || card[x][1][0] != card[x][2][0]) return;
sort(val[x],val[x] + 3);
stu[x].val = 40000000 + val[x][2] * 10000 + val[x][1] * 100 + val[x][0];
return;
}
void work4(int x)
{
if(card[x][0][0] == card[x][1][0] && card[x][1][0] == card[x][2][0]) return;
sort(val[x],val[x] + 3);
if(val[x][1] - val[x][0] == 1 && val[x][2] - val[x][1] == 1)
{ stu[x].val = 30000000 + val[x][0];return; }
if(val[x][0] == 2 && val[x][1] == 3 && val[x][2] == 14) { stu[x].val = 30000000 + 1;return;}
}
void work5(int x)
{
sort(val[x],val[x] + 3);
if(val[x][0] == val[x][1])
stu[x].val = 20000000 + val[x][1] * 100 + val[x][2];
if(val[x][1] == val[x][2])
stu[x].val = 20000000 + val[x][1] * 100 + val[x][0];
return;
}
void work6(int x)
{
sort(val[x],val[x] + 3);
stu[x].val = val[x][2] * 10000 + val[x][1] * 100 + val[x][0];
}
void work()
{
scanf("%d",&n);
for(int i = 1;i <= n; i++)
cin >> stu[i].nam >> card[i][0] >> card[i][1] >> card[i][2];
for(int i = 1;i <= n; i++)
for(int j = 0;j <= 2; j++)
{
if(card[i][j].length() == 3) val[i][j] = 10;
else if('2' <= card[i][j][1] && card[i][j][1] <= '9') val[i][j] = card[i][j][1] - '0';
else if(card[i][j][1] == 'J') val[i][j] = 11;
else if(card[i][j][1] == 'Q') val[i][j] = 12;
else if(card[i][j][1] == 'K') val[i][j] = 13;
else if(card[i][j][1] == 'A') val[i][j] = 14;
}
for(int i = 1;i <= n; i++)
{
work6(i);work5(i);work4(i);work3(i);work2(i);work1(i);
}
sort(stu + 1,stu + n + 1);
for(int i = 1;i <= n; i++)
cout << stu[i].nam << endl;
}
int main()
{
int t;scanf("%d",&t);
while(t --) work();
}