Translations
InterviewTime limit1sMemory limit128 MB
Given two alphabetically sorted lists of two-word phrases in two languages, reconstruct the unknown one-to-one word translation mapping. Print each source word with its translation, sorted.
- Level
Medium6 of 10
- Topics
- Graph, Hash map, Sorting, Implementation
- Solved
- No attempts yet
Problem
Bob Roberts is responsible for translating documents between different languages. To help him, his managers give him translation files that always come in pairs: one file lists sample phrases in one language, and the other lists their translations into a second language. Unfortunately, an overeager assistant sorted the contents of every file alphabetically, destroying the correspondence between each phrase and its translation. Luckily, the lists are complete enough that the original pairing can be reconstructed from the sorted lists alone. This works especially well when every phrase consists of exactly two words.
For example, consider these two lists:
From them we can deduce that arlo means hot, zym means seat, flub means school, pleve means bus, and dourm means stop.
The translation is word-for-word and position-preserving: each language-1 word has exactly one language-2 translation, and if a language-1 phrase is x y, its language-2 counterpart is f(x) f(y), where f is the unknown word-to-word mapping. Given the two sorted lists, recover f.
Input
The input contains several test cases. Each test case begins with a line holding a positive integer (), the number of two-word phrases in each language. The next lines list the phrases of the first language in alphabetical order, one phrase per line. The following lines list the phrases of the second language in alphabetical order, one per line. Each phrase is two words separated by a single space, and every word uses only upper- and lower-case letters.
Within a single test case there are at most 25 distinct words. No word is the first word of more than 10 phrases in a language, and likewise no word is the last word of more than 10 phrases. A line containing a single 0 follows the last test case and marks the end of the input.
Output
For each test case, print one line of the form
word1/word2
for every distinct word of the first language, where word2 is its translation in the second language and a single slash separates the two words. Sort the lines by the first-language word and print each first-language word exactly once. The output must contain no spaces. Separate the outputs of consecutive test cases with a single blank line. Each test case is guaranteed to have a unique correct reconstruction.