TopCoder problem "StickedWords" used in SRM 291 (Division I Level Three)



Problem Statement

    

We have a dictionary of words dict, and we are writing words down in a single line using the following rules. The first written word can be any word from dict. Each subsequent written word must start with the same letter as the last letter of the previous written word, and that shared letter is only written once (see examples). Only words from dict can be used, but each word can be used an unlimited number of times.

Using the rules above, construct the lexicographically earliest line with length greater than or equal to len characters. Return an empty String ("") if such a line cannot be constructed.

 

Definition

    
Class:StickedWords
Method:constructLine
Parameters:String[], int
Returns:String
Method signature:String constructLine(String[] dict, int len)
(be sure your method is public)
    
 

Constraints

-dict will contain between 1 and 50 elements, inclusive.
-Each element of dict will contain between 2 and 50 characters, inclusive.
-Each element of dict will contain only lowercase letters ('a'-'z').
-len will be between 1 and 2500, inclusive.
 

Examples

0)
    
{"salad", "sandwich", "hamburger", "rings"}
35
Returns: "hamburgeringsandwichamburgeringsalad"
The first word in the line is "hamburger". The next word must start with the letter 'r', so we write "rings". Notice that we only write the shared 'r' once, so at this point, the line is "hamburgerings". The rest of the words, in order, are: "sandwich", "hamburger", "rings", and "salad". The resulting line is 36 characters long, and is the lexicographically earliest possible line containing at least 35 characters.
1)
    
{"salad", "hamburger", "rings"}
35
Returns: ""
2)
    
{"aba", "aac", "czz"}
10
Returns: "abababaaczz"
3)
    
{"aarb", "bcb", "bbd", "dzz"}
15
Returns: "aarbcbcbcbcbbdzz"
4)
    
{"abd", "dgga", "abdg", "gga", "gg", "gaader"}
22
Returns: "abdggabdggabdggabdgaader"

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5954

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=9812&pm=5954

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem categories:

Dynamic Programming, Graph Theory