Ambiguous
Time limit1sMemory limit128 MB
Split a scrambled, space-free string into a unique sequence of dictionary words matching letter multisets, first and last letters, reporting ambiguity or impossibility.
- Level
Medium7 of 10
- Topics
- Dynamic programming, String, Hash map, Backtracking
- Solved
- No attempts yet
Problem
Even if you shuffle every letter of a word except its first and last letter, a person can still read the word without much trouble. For example, most people can easily read the sentence "tihs snetncee mkaes prfecet sesne".
Likewise, removing all the spaces between words does not make a sentence much harder to read. For example, "thissentencemakesperfectsense" is still readable.
However, doing both at once — shuffling the interior letters and removing the spaces — makes a sentence hard to read. A sentence such as "tihssnetnceemkaesprfecetsesne" is an example.
You are given a sentence in which, for every word, the first and last letters were kept in place while the interior letters were permuted arbitrarily, and then all spaces between words were removed. You are also given a list of valid words. Using this information, write a program that reconstructs the original sentence.
A fragment (one original word) matches a valid word when they have the same length, the same first letter, the same last letter, and the same multiset of letters (each letter used the same number of times).
Input
The first line contains the number of test cases . ()
Each test case consists of two parts.
- The first line: the sentence with interior letters shuffled and spaces removed. It consists of lowercase English letters only and has length at most .
- The second line: the number of valid words . ()
- The next lines: the valid words. All are distinct, consist of lowercase English letters only, and have length at most .
Output
For each test case, print the result on its own line.
- If the original sentence can be reconstructed uniquely, print it, separating consecutive words with a single space.
- If there are two or more ways to reconstruct it, print
ambiguous. - If reconstruction is impossible, print
impossible.