Optimal Keypad
Time limit1sMemory limit128 MB
Split a 30-character alphabet tape into 12 labeled pieces to minimize total keystrokes for a word dictionary, printing the lexicographically smallest optimal cut string.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Prefix sum, Binary search
- Solved
- No attempts yet
Problem
A mobile phone has a keypad of 12 keys, numbered 1 to 12. Each key is labeled with a string of characters. To type the -th character of a key's string, you press that key times. The goal is to assign character strings to the keys so that typing words drawn from a dictionary of common words takes as few keystrokes as possible on average.

Figure 1
Take the 30 characters written on a label tape in exactly this order. Cut the tape into 12 non-empty pieces, each containing one or more consecutive characters. Number the pieces (labels) to from left to right and assign label to key . Within a label, the first character costs keystroke, the second costs , and in general the -th character costs keystrokes.

Figure 2
For a given dictionary, choose the 11 cutting positions that minimize the total number of keystrokes needed to type every word (which is the same as minimizing the average number of keystrokes per word). The answer is reported as a string of 11 characters in which the -th character is the first character of label ; the first character of label is always , so it is omitted.
Input
The first line contains an integer (), the number of test cases. Each test case begins with a line containing an integer (), the number of common words. Each of the next lines contains one common word. Every word consists of at most 30 characters from the alphabet .
Output
For each test case, print one line containing an optimal cut string. Because several cut strings may achieve the minimum, print the one that is smallest in lexicographic order.