# Arup Guha
# 2/19/2025
# Solution to COP 4516 Final Individual Contest Problem C: Which Group?

nC = int(input())

# Process cases.
for loop in range(nC):

    # Get num names, queries.
    toks = input().split()
    n = int(toks[0])
    numQ = int(toks[1])

    # Add each entry into a dictionary.
    group = {}
    for i in range(n):
        toks = input().split()
        group[toks[0]] = int(toks[1])

    # Process queries.
    for i in range(numQ):

        # Get name.
        name = input().strip()

        # Was listed so go to map.
        if name in group:
            print(group[name])

        # Not in group.
        else:
            print(-1)
        
