Railroad
InterviewTime limit1sMemory limit128 MB
Given train schedules with stop times, find the journey from a start city to a destination leaving no earlier than a given time, minimizing arrival time and then maximizing departure.
- Level
Medium6 of 10
- Topics
- Graph, Shortest path, Sorting, Implementation
- Solved
- No attempts yet
Problem
Early tomorrow morning Jill must travel from one city to another to reach a programming contest. To avoid arriving too late and being shut out, she wants to reach her destination as early as possible. But she also dislikes waiting at the station, so if several journeys arrive at the same time she picks the one that departs from the start city as late as possible.
You are given several train schedules. For a given start city, destination city, and earliest possible departure time, find the connection that reaches the destination at the earliest possible arrival time. If several connections share that earliest arrival time, choose the one whose departure from the start city is as late as possible.
Changing trains takes no time at all: Jill can switch trains instantaneously (in zero time). She may board or get off a train at any of the stops it makes.
Input
The input contains several scenarios. Each scenario has three parts.
Part 1 — cities. A line with an integer (), followed by lines, each containing one city name. City names consist of letters only.
Part 2 — trains. A line with an integer (), followed by train descriptions. Each train description begins with a line containing an integer (), followed by lines, each containing a time and a city name. Such a line means the train stops at that city at that time, where a passenger may board or get off. Times use the 24-hour format hhmm.
Part 3 — the query. Three lines: the earliest possible departure time, the name of the start city, and the name of the destination city. The start and destination cities are always different.
A line containing a single in place of marks the end of the input and must not be processed.
Output
For each scenario, first print a line Scenario #n, where is the scenario number starting from .
If a connection exists, print two more lines. The first line is Departure, the departure time (four digits, zero-padded), and the start city. The second line is Arrival, the arrival time (four digits, zero-padded), and the destination city. Pad with spaces so the times line up: exactly as in the example, Departure is followed by one space and Arrival by three spaces.
If no connection reaches the destination on the same day (that is, before midnight), print a single line No connection instead.
Separate consecutive scenarios with a single blank line.