YetAnotherHamiltonianPath
SRM 496 · 2010-11-01 · by gojira_tc
Problem Statement
You're given a graph where the i-th (0-based) vertex is labeled with
Return the minimum possible cost of a Hamiltonian path which starts at vertex 0 and ends at vertex 1.
Notes
- A prefix of string S is a string that can be obtained by removing zero or more contiguous characters from the end of S.
- The longest common prefix of two strings A and B is the longest possible string which is a prefix of both A and B.
Constraints
- label will contain between 2 and 50 elements, inclusive.
- Each element of label will be between 1 and 50 characters long, inclusive.
- Each element of label will consist of lowercase letters ('a'-'z') only.
{"home", "school", "pub"}
Returns: 70
The only possible Hamiltonian path from vertex 0 to vertex 1 is 0->2->1. Vertex 0 is labeled "home", and vertex 1 is labeled "pub", so since these two strings have no common prefix, the cost of the edge 0->1 is 4^2+3^2=25. The cost of the edge 2->1 is 45, so the total cost of the path is 70.
{"school", "home", "pub", "stadium"}
Returns: 167
Of the two possible Hamiltonian paths, the cost of the one that visits "stadium" right after "school" is 1 less than the other one's.
{"abcd","aecgh","abef","aecd"}
Returns: 91
The cost matrix of this graph is: -- 40 28 31 40 -- 40 32 28 40 -- 31 31 32 31 -- The optimal path is "abcd"->"abef"->"aecd"->"aecgh".
{"manglisi", "tbilisi"}
Returns: 113
{"a","a"}
Returns: 1
Submissions are judged against all 133 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class YetAnotherHamiltonianPath with a public method int leastCost(vector<string> label) · 133 test cases · 2 s / 256 MB per case