// Arup Guha
// 2/18/2205
// Solution to Final Individual Contest Problem C: Which Group?

import java.util.*;

public class group {

	public static void main(String[] args) {
	
		Scanner stdin = new Scanner(System.in);
		int nC = stdin.nextInt();
		
		// Process cases.
		for (int loop=0; loop<nC; loop++) {
		
			// Get num students, queries
			int n = stdin.nextInt();
			int nQ = stdin.nextInt();
			
			// Store both teams.
			HashSet<String> one = new HashSet<String>();
			HashSet<String> two = new HashSet<String>();
			
			// Get names.
			for (int i=0; i<n; i++) {
				String name = stdin.next();
				int team = stdin.nextInt();
				
				// Add to appropriate team.
				if (team == 1) 
					one.add(name);
				else
					two.add(name);
			}
			
			// Process queries.
			for (int i=0; i<nQ; i++) {
				String name = stdin.next();
				
				// Look up and print accordingly.
				if (one.contains(name))
					System.out.println(1);
				else if (two.contains(name))
					System.out.println(2);
				else
					System.out.println(-1);
			}
		}
	}
}