← 返回 pinterest 的题目列表Reconstruct Itinerary (with loop/cycle follow-up)
类型:online_judge
You are given a list of airline tickets tickets, where tickets[i] = [from, to] represents a flight from airport from to airport to. Reconstruct an itinerary that:
Uses all tickets exactly once.
Starts from "JFK".
If multiple valid itineraries exist, returns the lexicographically smallest itinerary when comparing the entire airport sequence.
The directed graph may contain loops/cycles and duplicate edges.
Output the reconstructed itinerary as a list of airport codes.
Input format
Line 1: integer n (# of tickets)
Next n lines: two strings from to
Output format
One line: the airport sequence separated by spaces.
Typical constraints
1 <= n <= 2*10^5
Example Input:
5
JFK SFO
JFK ATL
SFO ATL
ATL JFK
ATL SFO
Output:
JFK ATL JFK SFO ATL SFO
Example
Input
5
JFK SFO
JFK ATL
SFO ATL
ATL JFK
ATL SFO
Output
JFK ATL JFK SFO ATL SFO