Booking Error
Time limit1sMemory limit128 MB
Add the fewest new segments to the booked ticket so travel from start to destination uses the smallest number of stops the network allows.
- Level
Medium6 of 10
- Topics
- Shortest path, Dynamic programming, BFS
- Solved
- No attempts yet
Problem
Your boss is upset. The flight to the United States that his secretary booked is wrong: he wanted a trip with as few transit stops as possible, and the booked segments do not give him that. The segments are already paid for and stay on the ticket, so he wants you, the programmer, to fix the trip by booking as few new segments as possible.
You are given every direct connection between two airports. Each connection can be flown in both directions. You are also given the segments the secretary already booked, in the order they appear on the ticket. The trip starts at the first airport of the ticket and ends at the last one.
Book the smallest number of extra segments so that your boss can travel from the start to the destination in the smallest number of segments that the direct connections allow at all.
The booked segments are flexible in timing and can be flown in any order. Your boss may fly all of them, some of them, or none of them, together with the segments you add. A segment booked from A to B can only be flown from A to B, never from B to A.
Input
The first line contains the number of test cases . () Each test case is given in lines.
The first line of a test case contains the number of direct connections . () Each of the next lines contains the names of two different airports joined by a direct connection, which can be flown in both directions. An airport name is exactly three capital letters. Inside one test case there is at most one connection between any pair of airports.
The last line of a test case holds the faulty ticket as , where is the number of segments already booked and each is an airport name. Every two consecutive names mean one segment booked from the earlier airport to the later one. The bookings are faulty enough to revisit airports and even to book the same segment more than once, but every booked segment is one of the connections above. Your boss starts at and his destination is .
Output
For each test case, print on its own line the smallest number of segments that have to be booked so that, combined with the segments already booked, your boss can go from to in the smallest possible number of segments.
Hint
In the first test case of the sample, booking FRA to JFK or booking CAI to LHR lets the boss fly from CAI to JFK with one stop, which is the fewest stops possible.
In the second test case the fewest stops can only be reached along CAI, FRA, LHR, JFK. The secretary booked LHR to FRA and not the other direction, so FRA to LHR has to be booked.
In the third test case the secretary booked an optimal ticket, so nothing has to be added.