/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
{
List<String> towns = new ArrayList<>();
towns.add("Москва");
towns.add("Саратов");
towns.add("Свердловск");
towns.add("Астана");
towns.add("Астрахань");
towns.add("Санкт-петербург");
towns.add("Гурьев");
towns.add("Начало");
towns.add("Орёл");
towns.add("Липецк");
towns.add("Кишенёв");
towns.add("Владимир");
towns.add("Ростов");
towns.add("Воронеж");
towns.add("Житомир");
towns.add("Минск");
towns.add("Киров");
towns.add("Норильск");
towns.add("Муром");
towns.add("Донецк");
towns.add("Тьмутаракань");
towns.add("Омск");
towns.add("Каракум");
towns.add("Волгоград");
towns.add("Уфа");
towns.add("Тарту");
towns.add("Рига");
towns.add("Ю");
int max = 0;
List<String> result = new ArrayList<>();
TownsGame.maxDepth = 0;
TownsGame.maxHead = null;
new TownsGame(null, town, towns, 0);
if (TownsGame.maxHead != null) {
if (max < TownsGame.maxDepth) {
TownsGame h = TownsGame.maxHead;
result = new ArrayList<>();
while (h.parent != null) {
result.add(0, h.content);
h = h.parent;
}
max = TownsGame.maxDepth;
resultStart = town;
}
}
}
System.
out.
println("[" + resultStart
+ "]"); for (int i = 0; i < result.size(); i++) {
System.
out.
print(result.
get(i
)); if (i
< result.
size() - 1) System.
out.
print(" -> "); }
}
public static class TownsGame {
final TownsGame parent;
final List<String> usable;
final List<TownsGame> next;
static int maxDepth = 0;
static TownsGame maxHead;
public TownsGame
(TownsGame parent,
String content, List
<String
> usable,
int depth
) { this.parent = parent;
this.content = content;
this.usable = new ArrayList<>(usable);
this.usable.remove(content);
this.next = new ArrayList<>();
boolean nextT = false;
for (int i = 0; i < this.usable.size(); i++) {
if (this.usable.get(i).length() < 1) continue;
char fChar
= Character.
toLowerCase(this.
usable.
get(i
).
charAt(0)); char eChar
= Character.
toLowerCase(content.
charAt(content.
length() - 1)); if (eChar == 'ь') {
if (content.length() < 2) continue;
eChar = content.charAt(content.length() - 2);
}
if (fChar == eChar) {
next.add(new TownsGame(this, this.usable.get(i), this.usable, depth + 1));
nextT = true;
}
}
if (!nextT) {
if (depth > maxDepth) {
maxDepth = depth;
maxHead = this;
}
}
}
}
}