#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char name[11];
char suit[3];
int point[3];
int weight;
int mpoint;
}PLAYER;
int IsSuit(PLAYER pl);
int IsFlush(PLAYER pl);
int IsFS(PLAYER pl);
int IsHouse(PLAYER pl);
int Find(PLAYER pl);
int cmpP(const void* a, const void* b)
{
return *(int*)a - *(int*)b;
}
int cmpW(const void* a, const void* b)
{
PLAYER* p1 = (PLAYER*)a;
PLAYER* p2 = (PLAYER*)b;
if (p1->weight != p2->weight)
return p1->weight - p2->weight;
else if (p1->mpoint != p2->mpoint)
return p1->mpoint - p2->mpoint;
else return strcmp(p1->name, p2->name);
}
int main(void)
{
int T;
scanf("%d", &T);
int n;
int t, i, j;
for (t = 0; t < T; t++)
{
scanf("%d", &n);
PLAYER player[100] = { 0 };
char ch;
for (i = 0; i < n; i++)
{
scanf("%s", player[i].name);
for (j = 0; j < 3; j++)
{
scanf(" %c", &player[i].suit[j]);
scanf(" %c", &ch);
getchar();
if (ch >= '2' && ch <= '9')
player[i].point[j] = ch - '0';
else
{
switch (ch)
{
case '1':player[i].point[j] = 10; break;
case 'J':player[i].point[j] = 11; break;
case 'Q':player[i].point[j] = 12; break;
case 'K':player[i].point[j] = 13; break;
case 'A':player[i].point[j] = 14; break;
}
}
}
qsort(player[i].point, 3, sizeof(int), cmpP);
player[i].weight = IsHouse(player[i]);
if (player[i].weight != 6)
player[i].weight = IsFS(player[i]);
if (player[i].weight != 2)
player[i].mpoint = 10000 * player[i].point[2] + 100 * player[i].point[1] + player[i].point[0];
else
player[i].mpoint = Find(player[i]);
}
qsort(player, n, sizeof(PLAYER), cmpW);
for (i = n - 1; i >= 0; i--)
printf("%s\n", player[i].name);
}
}
int Find(PLAYER pl)
{
if (pl.point[0] == pl.point[1])
return 100 * pl.point[0] + pl.point[2];
else if (pl.point[0] == pl.point[2])
return 100 * pl.point[0] + pl.point[1];
else return 100 * pl.point[1] + pl.point[0];
}
int IsHouse(PLAYER pl)
{
if (pl.point[0] == pl.point[1] && pl.point[0] == pl.point[2])
return 6;
else if (pl.point[0] == pl.point[1] || pl.point[0] == pl.point[2] || pl.point[1] == pl.point[2])
return 2;
else return 1;
}
int IsFS(PLAYER pl)
{
int ff = IsFlush(pl);
int ss = IsSuit(pl);
if (ff & ss)
return 5;
else if (ss)
return 4;
else if (ff)
return 3;
else return pl.weight;
}
int IsFlush(PLAYER pl)
{
if (pl.point[0] == pl.point[1] - 1 && pl.point[1] == pl.point[2] - 1)
return 1;
else return 0;
}
int IsSuit(PLAYER pl)
{
if (pl.suit[0] == pl.suit[1] && pl.suit[0] == pl.suit[2])
return 1;
else return 0;
}