All problems

Problem 627

Reconstruct Itinerary

Hard · 30 pts · Graph, Depth-First Search, Eulerian Path

Problem

You are given a list of airline tickets, each from one airport to another (three-letter codes). All the tickets belong to one traveller who starts at JFK and uses every ticket exactly once. Reconstruct the itinerary; if several itineraries are possible, print the one that is lexicographically smallest when read as a sequence of codes. At least one valid itinerary always exists. Hierholzer's algorithm finds it: keep each airport's destinations sorted, always take the smallest unused one, and add an airport to the route when it has no tickets left.

Input

The first line contains M, the number of tickets. Each of the next M lines contains two airport codes FROM and TO.

Output

Print the itinerary, M + 1 airport codes separated by spaces.

Constraints

1 <= M <= 300; codes are three uppercase letters; a valid itinerary from JFK exists

Example input

5
JFK SFO
JFK ATL
SFO ATL
ATL JFK
ATL SFO

Example output

JFK ATL JFK SFO ATL SFO

Explanation

With tickets JFK→SFO, JFK→ATL, SFO→ATL, ATL→JFK and ATL→SFO, both JFK ATL JFK SFO ATL SFO and JFK SFO ATL JFK ATL SFO use every ticket, and the first is lexicographically smaller.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Sliding Puzzle Next: Course Schedule IV