This page is still under construction.

Parts of this page are still being built. What you see may change.

Optimal Keypad

Time limit1sMemory limit128 MB

Summary
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 nn-th character of a key's string, you press that key nn 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

Figure 1

Take the 30 characters {a,b,c,…,z,+,∗,/,?}\{a, b, c, \dots, z, +, *, /, ?\} 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) 11 to 1212 from left to right and assign label kk to key kk. Within a label, the first character costs 11 keystroke, the second costs 22, and in general the nn-th character costs nn keystrokes.

Figure 2

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 ii-th character is the first character of label i+1i+1; the first character of label 11 is always aa, so it is omitted.

Input

The first line contains an integer tt (1≤t≤101 \le t \le 10), the number of test cases. Each test case begins with a line containing an integer MM (1≤M≤100001 \le M \le 10000), the number of common words. Each of the next MM lines contains one common word. Every word consists of at most 30 characters from the alphabet {a,b,c,…,z,+,∗,/,?}\{a, b, c, \dots, z, +, *, /, ?\}.

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.

Examples3

  1. Example 1

    Input
    2
    2
    hi
    ok
    5
    hello
    bye
    how
    when
    who
    
    Expected output
    bcdefghijko
    bcdefhlnowy
    
  2. Example 2

    Input
    1
    1
    a
    
    Expected output
    bcdefgh+*/?
    
  3. Example 3

    Input
    1
    5
    abcdef
    ghijkl
    mnopqr
    stuvwx
    yz+*/?
    
    Expected output
    cegikmpsvy*