public static void main(String[] args) throws Throwable{
		Escaner sc = new Escaner();
		StringBuilder sb = new StringBuilder();
		for (int c = 0, C = sc.nextInt(); c < C; c++) {
			int D = sc.nextInt();
			int[][] shuffle = new int[D][52];
			for (int i = 0; i < shuffle.length; i++) 
				for (int j = 0; j < shuffle[i].length; j++) 
					shuffle[i][j] = sc.nextInt() - 1;
			int[] inicial = new int[52];
			for (int i = 0; i < inicial.length; i++) 
				inicial[i] = i;
			for (String ln; (ln = sc.in.readLine()) != null && !ln.equals(""); ) {
				int s = Integer.parseInt(ln.trim()) - 1;
				int sol[] = new int[52];
				for (int i = 0; i < shuffle[s].length; i++)
					sol[i] = inicial[shuffle[s][i]];
				inicial = sol;
			}
			for (int i = 0; i < inicial.length; i++) 
				sb.append(getCarta(inicial[i]) + "\n");
			if(c < C-1)sb.append("\n");
		}
		System.out.print(new String(sb));
	}