# Kyle Dencker
# 7/24/2013
# Solution to SI@UCF Contest Question: Say What

# Open the file.
file=open('saywhat.in')
cycles=int(file.readline())

# Used for each case.
wordlist = { }

# Returns true if key_name is in our dictionary.
def has_key(key_name):
    for key in wordlist.keys():
        if key == key_name:
            return True

    return False;

# Go through each case.
for i in range(cycles):

    wordlist.clear()

    numWords = int(file.readline())

    # Read in the words and add both pairs to the dictionary.
    for j in range(numWords):
        words=file.readline().split()
        wordlist[words[0]] = words[1]
        wordlist[words[1]] = words[0]

    # Go through each sentence.
    testCases = int(file.readline())
    for j in range(testCases):

        # Parse the line.
        words = file.readline().split()
        numOfWords = int(words[0])

        # Go through each word and replace if necessary.
        for k in range(numOfWords):
            theWord = words[k+1]
            if (has_key(theWord)):
                theWord = wordlist[theWord]

            # Make sure there's no space at the end.
            if k < numOfWords-1:    
                print(theWord, sep=' ', end=" ")
            else:
                print(theWord, end="")
                
        # Done with the sentence, move on.
        print()

# Close only when we're done.
file.close()


