Sort a scrambled itinerary (Large)
InterviewTime limit5sMemory limit512 MB
Rebuild the flight order by chaining tickets from the starting city that never appears as a destination.
- Level
Easy3 of 10
- Topics
- Hash map
- Solved
- No attempts yet
Problem
Mary bought a bundle of one way tickets that take her through several transfers. For example, SFO to DFW, DFW to JFK, JFK to MIA, MIA to ORD.
Transferring at the same city twice or more makes no sense, so Mary never buys such an itinerary.
After she received the tickets she shuffled them and forgot the original order. Write a program that sorts the shuffled tickets back into the real itinerary order.
Input
The first line contains the number of test cases . The test cases follow.
The first line of each test case contains the number of tickets . Then tickets follow, and each ticket takes two lines: the source on the first line and the destination on the second line. An airport code is three uppercase letters.
Output
For each test case, print one line in the form Case #x: itinerary, where is the test case number starting from 1 and itinerary is the list of tickets sorted into the real itinerary order. Write each ticket as source-destination and separate consecutive tickets with a single space.
Constraints
- The tickets of a test case are a shuffle of one itinerary Mary bought, so they always rebuild into one valid itinerary.
- No city is visited twice inside a test case, so the answer is unique.