16
1
If you like, write a program which sorts cities according to the rules of city name game.
Each name of the city should start from the last letter in the previous city name. E.g.
Lviv -> v -> Viden -> n -> Neapolis -> s -> Sidney -> y -> Yokogama -> a -> Amsterdam -> m -> Madrid -> d -> Denwer
In the sorted list first letter of the first city and last letter of the last
shouldn't match anythingdoesn't have to be the same letter.- You can assume city names have only letters.
- Program output should have same capitalization as input
Example:
% ./script Neapolis Yokogama Sidney Amsterdam Madrid Lviv Viden Denwer
["Lviv", "Viden", "Neapolis", "Sidney", "Yokogama", "Amsterdam", "Madrid", "Denwer"]
2Can we assume that there will always be a valid solution? – Gareth – 2012-07-16T16:00:03.467
@Gareth yes, you can – defhlt – 2012-07-16T16:02:19.487
the second rule - "[...] shouldn't match anything" - is it a requirement or just a statement saying that it's OK to have mismatch between the first and last letter? (ex: is a list like
["Viden" ... "Lviv"]
invalid?) – Cristian Lupascu – 2012-07-16T18:31:22.003@w0lf by "shouldn't" I meant it doesn't have to, it is not compulsory. So your example is valid. – defhlt – 2012-07-16T18:39:51.537
Hint: If you want a nice solution, you can reduce this to the calculation of eulerian paths, where each letter is a vertex and each word is an edge. (For instance, Berlin is the edge B → N) This is solvable in O(n), where n is the number of edges. – FUZxxl – 2012-07-17T22:56:46.287