public static void main(String [] args) throws FileNotFoundException {
		SortedSet<String> admitidas = new TreeSet<String>();
		Scanner sc = new Scanner(new File("boozle-dict.txt"));
		String last = "";
		while(sc.hasNextLine()) {
			last = sc.nextLine();
			admitidas.add(last);
		}
		sc.close();
		
		sc = new Scanner(System.in);
		int cases = Integer.parseInt(sc.nextLine());
		for(int i = 0; i<cases; i++) {
			Map<Character,Integer> letterScores = new HashMap<Character,Integer>();
			String punt = sc.nextLine();
			int time = 0, n = 0, m = 0;
			Casilla[][] tab;
			
			punt = punt.substring(1, punt.length()-1);
			StringTokenizer st = new StringTokenizer(punt, ", ");
			while(st.hasMoreTokens()) {
				letterScores.put(st.nextToken().charAt(1), Integer.parseInt(st.nextToken()));
			}
			time = Integer.parseInt(sc.nextLine());
			n = Integer.parseInt(sc.nextLine());
			m = Integer.parseInt(sc.nextLine());
			tab = new Casilla[n][m];
			for(int j = 0; j<n; j++) {
				st = new StringTokenizer(sc.nextLine());
				for(int k = 0; k<m; k++) {
					String a = st.nextToken();
					tab[j][k] = new Casilla(a.charAt(0),Integer.parseInt(a.substring(1,2)),
							Integer.parseInt(a.substring(2,3)));
				}
 			}
			solve(tab,admitidas,letterScores,time,last.length());
		}	
		sc.close();
	}