Studious Student

https://www.facebook.com/codingcompetitions/hacker-cup/2011/qualification-round/problems/C

Question

You've been given a list of words to study and memorize. Being a diligent student of language and the arts, you've decided to not study them at all and instead make up pointless games based on them. One game you've come up with is to see how you can concatenate the words to generate the lexicographically lowest possible string.

Input Format

As input for playing this game you will receive a text file containing an integer N, the number of words sets you need to play your game against. This will be followed by N word sets, each starting with an integer M, the number of words in the set, followed by M words. All tokens in the input will be separated by some whitespace and, aside from N and M, will consist entirely of lowercase letters.

Constraints

1N1001 \le N \le 100
1M91 \le M \le 9
1all_word_lengths101 \le all\_word\_lengths \le 10

Output Format

Your submission should contain the lexicographically shortest strings for each corresponding word set, one per line and in order.

Sample Inputs:

Input

Output


58/63 Test Cases Solved

This is the one which I am working during the contest, and sadly it didn't pass all test cases. This code uses a lambda anonymous key function, which first pad all the text into the longest word, and sort by the alphabetical order.

This may not work if the string has duplicated values.

Current Solution — Brute Force Permutation

The current working solution is simple — brute force all the permutation of the combinations and take the minimum as the result.

Personally, I am not a fan of using brute force to list out all possible combinations, but since it has only 63 test cases, I would take it.

Here's the solution, if you want simple and crude solution:

Note that I imported a library called itertools, which it may or may not work in different contests. Luckily this contest accepts the library imports. Another note: this took O(N!) time complexity.

Last updated