Dictionary
Time limit1sMemory limit128 MB
Given up to 50 short words, find the fewest vertices of an edge-labeled tree whose downward paths contain every word.
- Level
Hard8 of 10
- Topics
- Trie, String matching, Dynamic programming, Graph
- Solved
- No attempts yet
Problem
Petr and Dmitry are working on a new data compression scheme. Their job is to compress a given set of words, and the compressed form is a rooted tree. Every edge of the tree carries exactly one lowercase letter.
The dictionary produced by such a tree is defined as follows. Pick any vertex of the tree, walk down a path that always moves away from the root, and concatenate the letters written on the edges you pass. The word you read belongs to the dictionary. The first vertex of the walk does not have to be the root, and the last vertex does not have to be a leaf. The dictionary of the tree is the set of all words obtained this way.
The two of them need a tree whose dictionary contains every word of the given set, and among those trees they want one with the fewest vertices.
For example, consider the tree that is a single downward chain of five vertices whose edges read a, b, c, d from the root. Its dictionary contains a, ab, abcd, bc, cd and d, but neither ba nor ac.
Input
The first line contains the number of words n (). Each of the next n lines contains one word. The words are pairwise different, non-empty, and consist of lowercase English letters. Each word is at most 10 letters long.
Output
Print one line with the smallest number of vertices of a tree whose dictionary contains all n given words.
Notes
The five words north, eastern, european, regional and contest fit into a tree with 31 vertices. Write contest as one chain down from the root, start european at the e of contest so that both words use that one e edge, start eastern at the ea of european, start north at the last n of european, and start regional at the r of north. That puts all five words in the dictionary with 30 edges. The five words have 35 letters in total, so the shared edges save 5 of them.