Word Translation Lookup
Time limit12sMemory limit128 MB
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 in language corresponds to word in language .
Write a program that answers queries of the form: find every translation of word from language into language .
The translation relation is transitive: word in language is a translation of word in language whenever there is a chain of (word, language) pairs, each two adjacent pairs being direct translations of each other, that leads from to .
Formally, there must exist a sequence of (word, language) pairs such that is a direct translation of , is a direct translation of , , and is a direct translation of .
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 ().
Each test set is given as follows.
- The first line contains , the number of direct translations ().
- Each of the next lines contains four words , , , , meaning word in language and word in language are direct translations of each other.
- The next line contains , the number of queries ().
- Each of the next lines contains a query of three words , , .
Every word in the input has length at most and consists only of lowercase English letters (-). Words on a line are separated by a single space.
Output
For each query , print one line.
- Print
?if no translation of word into language can be inferred. - Otherwise print all translations of word into language in lexicographic order, separated by commas and no spaces.
Because every word is trivially connected to itself, when the queried word is itself included in the answer.
You may assume the total amount of data you need to print does not exceed .