import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class Forest { static final int MaxClearing = 500; static public Set trail[][]; public static void addTrail(int c1, int c2, Set animals) { trail[c1][c2] = animals; trail[c2][c1] = animals; } // find trail to neighboring clearing with animal a public static int findNeighbor(int c, String a) { for (int i = 0; i< MaxClearing; i++) { if (trail[c][i] != null) { for (String s : trail[c][i]) { if (a.equals(s)) return i; } } } return -1; } // find path in forest for target list public static Queue findPath(List target) { Queue path = new LinkedList(); int location = 0; path.offer(0); for (String a : target) { int x = findNeighbor(location, a); if (x == -1) return null; location = x; path.offer(x); } if (location != 0) return null; return path; } public static void main(String[] argv) { int c1 = 0, c2 = 0; trail = new HashSet[MaxClearing][MaxClearing]; Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { Scanner lsc = new Scanner(sc.nextLine()); // read in trails if (lsc.hasNextInt()) { c1 = lsc.nextInt(); c2 = lsc.nextInt(); Set animals = new HashSet(); while (lsc.hasNext()) { animals.add(lsc.next()); } addTrail(c1, c2, animals); continue; } // no more trails List targets = new ArrayList(); while (lsc.hasNext()) targets.add(lsc.next()); Queue q = findPath(targets); if (q == null) System.out.println("Failed"); else { System.out.print(q.poll()); while (!q.isEmpty()) { System.out.print(" "+q.poll()); } System.out.println(); } } } }