#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define POKER_CNT 52
#define LINE_BUF_CNT 6
static char s_Line[LINE_BUF_CNT];
void ShuffleOnPokers(int* target, int* shuffleMethod)
{
static int tmp[POKER_CNT + 1];
for (int i = 1; i <= POKER_CNT; ++i)
{
tmp[i] = target[shuffleMethod[i]];
}
for (int i = 1; i <= POKER_CNT; ++i)
{
target[i] = tmp[i];
}
}
char* s_PokerType[] = {"Clubs", "Diamonds", "Hearts", "Spades"};
void OutputPoker(int poker)
{
int typeIndex = (poker - 1) / 13;
poker = poker - 13 * typeIndex;
if (poker <= 9)
cout << (poker + 1);
else if (poker == 10)
cout << "Jack";
else if (poker == 11)
cout << "Queen";
else if (poker == 12)
cout << "King";
else if (poker == 13)
cout << "Ace";
cout << " of " << s_PokerType[typeIndex] << endl;
}
void OutputPokers(int* pokers)
{
for (int i = 1; i <= POKER_CNT; ++i)
{
OutputPoker(pokers[i]);
}
}
void DoShuffle(const vector<int*>& shuffleVec, const vector<int>& shuffleSteps)
{
int target[POKER_CNT + 1];
for (int i = 1; i <= POKER_CNT; ++i)
target[i] = i;
for(int i = 0; i < shuffleSteps.size(); ++i)
{
ShuffleOnPokers(target, shuffleVec[shuffleSteps[i]]);
}
OutputPokers(target);
}
void HandleDataSet()
{
int shuffleTypes = 0;
cin >> shuffleTypes;
// Init
vector<int*> shuffleVec;
for (int i = 0; i < shuffleTypes; ++i)
{
shuffleVec.push_back(new int[POKER_CNT + 1]);
for (int j = 1; j <= POKER_CNT; ++j)
{
int tmp;
cin >> tmp;
shuffleVec[i][j] = tmp;
}
}
// Get ShuffleSteps
vector<int> shuffleSteps;
char* tmp = fgets(s_Line, LINE_BUF_CNT, stdin); // Consume the '\n' right after the last poker of the last shuffle type.
while(tmp)
{
tmp = fgets(s_Line, LINE_BUF_CNT, stdin);
if (!tmp)
break;
if (s_Line[0] == '\n') // Check whether it is an empty line.
break;
int nLen = strlen(s_Line);
s_Line[nLen] = '\0';
shuffleSteps.push_back(atoi(s_Line) - 1);
}
DoShuffle(shuffleVec, shuffleSteps);
// Clear
for (int i = 0; i < shuffleTypes; ++i)
{
delete[] shuffleVec[i];
}
}
void DoWork()
{
int nDataSetCnt;
cin >> nDataSetCnt;
fgets(s_Line, LINE_BUF_CNT, stdin); // Consume the '\n' right after the test case count.
fgets(s_Line, LINE_BUF_CNT, stdin); // Consume the empty line after the test case count.
int i = 1;
while(i <= nDataSetCnt)
{
HandleDataSet();
if (i < nDataSetCnt)
cout << endl;
++i;
}
}
int main(int argc, char* argv[])
{
DoWork();
return 0;
}