WORDRING - Word Rings

no tags 

A word ring is a sequence of words where the last two letters of each word are the same as the first two letters of the next word (and the last two letters of the last word are the same as the first two letters of the first word). For example, the following sequence is a word ring:


Your task is to write a program that, given a list of words, finds a word ring. You have to make the word ring as impressive as possible: the average length of the words in the ring has to be as large as possible. In the above example, the average length is (20 + 21 + 24)/3 = 21.6666 , which makes it somewhat impressive. Note that each word can be used at most once in the ring, and the ring can consist of a single word.


The input contains several blocks of test cases. Each case begins with a line containing a single integer 1 <= n <= 100000 , the number of possible words that can be used. The next n lines contain these words. The words contain only the characters 'a'-'z' and the length of each word is at most 1000.

The input is terminated by a block with n = 0.


For each test case in the input, you have to output a single number on a separate line: the maximum average length of a ring composed from (a subset of) the words given in the input. The average length should be presented as a real number with two digits of precision. If it is not possible to compose a ring from these words, then output 'No solution.' (without quotes). To avoid rounding problems, we accept solutions with a maximum of 0.01(positive or negative) error.



Warning: large input/output data, be careful with certain languages

hide comments
John Chen: 2016-09-02 09:46:02


Goran Zuzic: 2015-05-17 11:53:30

It seems that the input contains words of length 1. How should we handle such a case?

Vladimir Chalyshev: 2012-05-07 19:18:21

It's minimum mean weight cycle problem. The exist O(E*V) algorithms by Karp (The exist some ideas of algorithm in Cormen's Introduction to Algorithms).
Without any optimizations it gives 5.64s.

Phạm Lê Quang: 2009-04-24 13:36:31

Using Ford-Bellman to find negative cycle got TLE.
Is there a better solution for this problem?

Added by:Fudan University Problem Setters
Time limit:3s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: C99 ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:ACM Central European Programming Contest, Budapest 2005