The Concatenation of Words
InterviewTime limit1sMemory limit128 MB
Count the increasing selections of given words whose concatenation equals a pattern, capped at 1000000, and print the lexicographically smallest selection.
- Level
Medium6 of 10
- Topics
- Dynamic programming, String, Greedy
- Solved
- No attempts yet
Problem
We are given a pattern word and a finite sequence of nonempty words . We want to select some words of and concatenate them in the same order in which they appear in (that is, choosing a strictly increasing sequence of indices) so that the concatenation equals the pattern . Each word may be used at most once, and the chosen indices must be strictly increasing.
The pattern and every word of consist only of lowercase English letters ('a' to 'z'), carry no diacritics, and have length at most 150 each. The number of words satisfies .
For example, the pattern rytter can be formed from by choosing the words at indices (2, 4, 5, 7, 9), giving r + y + tt + e + r. Choosing indices (1, 5, 10), giving ry + tt + er, is another way to obtain the same pattern.
We want two things: how many such selections exist, and, among all of them, the lexicographically smallest one.
Write a program that:
- reads the pattern , the number of words , and the words of ;
- prints the single word
NIEif there is no way to form the pattern by concatenating a strictly increasing selection of words of ; - otherwise prints the number of valid selections (the exact count when it is at most 999999, or 1000000 when it is 1000000 or more), then the lexicographically smallest valid selection, giving the chosen indices in increasing order, one per line.
The lexicographic order on index sequences compares them element by element: at the first position where two sequences differ, the one with the smaller index is smaller, and if one sequence is a proper prefix of the other, the shorter one is smaller.
Input
- The first line contains one word of at most 150 lowercase English letters, the pattern .
- The second line contains a positive integer (), the number of words of the sequence .
- Each of the next lines contains one word of in order. Each word is nonempty, consists of at most 150 lowercase English letters, starts at the first character of its line, and ends right after its last letter.
Output
Print:
- the single word
NIEwhen it is impossible to form the pattern from the words of under the rules above; or - on the first line, the number of valid selections. This is the exact count when it is at most 999999, and exactly 1000000 when the true count is 1000000 or more. On the following lines, print the indices of the words forming the lexicographically smallest valid selection, in increasing order, one per line.