This page is still under construction.

Parts of this page are still being built. What you see may change.

Word Translation Lookup

Time limit12sMemory limit128 MB

Summary
Given pairs of directly translated words, list every target-language word linked to each query word through translation chains.
Level

Medium5 of 10

Topics
Union-find, Hash map, Sorting
Solved
No attempts yet

Problem

You are given a very long list of direct word-to-word translations between languages. Each entry has the form: word S1S_1 in language AA corresponds to word S2S_2 in language BB.

Write a program that answers queries of the form: find every translation of word SS from language AA into language BB.

The translation relation is transitive: word S2S_2 in language BB is a translation of word S1S_1 in language AA whenever there is a chain of (word, language) pairs, each two adjacent pairs being direct translations of each other, that leads from (S1,A)(S_1, A) to (S2,B)(S_2, B).

Formally, there must exist a sequence of (word, language) pairs (Xi,Ji)(X_i, J_i) such that (S1,A)(S_1, A) is a direct translation of (X1,J1)(X_1, J_1), (X1,J1)(X_1, J_1) is a direct translation of (X2,J2)(X_2, J_2), …\dots, and (Xk,Jk)(X_k, J_k) is a direct translation of (S2,B)(S_2, B).

The direct-translation relation is symmetric: each entry in the list means the two words are translations of each other.

Input

The first line contains the number of test sets ZZ (1≤Z≤101 \le Z \le 10).

Each test set is given as follows.

  • The first line contains NN, the number of direct translations (1≤N≤400001 \le N \le 40000).
  • Each of the next NN lines contains four words S1S_1, AA, S2S_2, BB, meaning word S1S_1 in language AA and word S2S_2 in language BB are direct translations of each other.
  • The next line contains MM, the number of queries (1≤M≤100001 \le M \le 10000).
  • Each of the next MM lines contains a query of three words SS, AA, BB.

Every word in the input has length at most 2020 and consists only of lowercase English letters (aa-zz). Words on a line are separated by a single space.

Output

For each query (S,A,B)(S, A, B), print one line.

  • Print ? if no translation of word SS into language BB can be inferred.
  • Otherwise print all translations of word SS into language BB in lexicographic order, separated by commas and no spaces.

Because every word is trivially connected to itself, when A=BA = B the queried word SS is itself included in the answer.

You may assume the total amount of data you need to print does not exceed 20 MB20\,\text{MB}.

Examples1

  1. Example 1

    Input
    2
    2
    drzwi pl door en 
    puerta es door en 
    2
    drzwi pl es
    door en pl
    3
    a x b y
    b y c y
    c y d y
    3
    a x y
    d y y
    acc tle wa
    
    Expected output
    puerta
    drzwi
    b,c,d
    b,c,d
    ?