LA 3531

LA 3531 - Word Rings

 * http://acmicpc-live-archive.uva.es/nuevoportal/data/problem.php?p=3531

Summary
Given is a set of words. A word ring is a sequence of words such that each word begins with the last two letters of the previous one (and the first word begins with the last two letters of the last word).

Find the maximal average word length a valid word ring can have.

Explanation
Consider a graph where vertices correspond to pairs of letters. Each word corresponds to a weighted directed edge in this graph.

We will use binary search on the interval [0, maximum word length] to find the answer.

We need to be able to answer the following question: "Does our graph contain a cycle with average edge length greater than W?".

This can be checked as follows: Modify each edge length from (say) x to W-x. Now we want to check whether our graph contains a negative cycle. This can be done using the Bellman-Ford algorithm. (Add a new "source" vertex v, connect it to all other vertices and check for negative cycles reachable from v.)

Input
3 intercommunicational alkylbenzenesulfonate tetraiodophenolphthalein 0

Output
21.66