Dividing the names
Time limit3sMemory limit256 MB
Split 2N names into N streets and N avenues so the total length of shortest unique prefixes on all N by N crossing signs is minimal.
- Level
Medium7 of 10
- Topics
- Trie, Dynamic programming
- Solved
- No attempts yet
Problem
The queen of Nlogonia is moving the capital to a new city called Sortonia. The plan for the city is an grid: avenues run north to south and streets run east to west. Every avenue crosses every street, and no two avenues and no two streets cross each other.
The city is almost finished, so the streets and the avenues need names. The citizens already voted on the names they want, but nobody has decided which of those names go to the streets and which go to the avenues. The decision matters, because every crossing carries a sign naming the street and the avenue that meet there, and the queen ordered the letters on those signs to be written in gold set with rubies.
You keep the accounts, so you have to make the total number of letters on the signs as small as possible. Your idea is to abbreviate the names. The abbreviation of an avenue name is the shortest prefix of that name which is not a prefix of any other avenue name, and the abbreviation of a street name is the shortest prefix which is not a prefix of any other street name. Each abbreviation therefore depends on how the names are split into street names and avenue names.
Take with the chosen names GAUSS, GALOIS, ERDOS and EULER. If the streets are GAUSS and GALOIS while the avenues are ERDOS and EULER, the abbreviations are GAU, GAL, ER and EU, the four signs read GAU|ER, GAU|EU, GAL|ER and GAL|EU, and 20 letters are written. Naming the streets GAUSS and ERDOS while the avenues are GALOIS and EULER is cheaper: the abbreviations become G, E, G and E, the signs read G|G, G|E, E|G and E|E, and only 8 letters are written.
No chosen name is a prefix of another chosen name, so every abbreviation exists. Compute the smallest total number of letters on the signs over all ways of splitting the names.
Input
The first line contains an integer (), the number of streets and also the number of avenues. Each of the next lines contains one chosen name, a non-empty string of at most 18 uppercase letters. No name in the input is a prefix of another name in the input.
Output
Print one integer, the smallest total number of letters written on the signs when the names are split optimally.