Traffic Lights
Time limit1sMemory limit128 MB
Find the earliest arrival time from a source to a destination on a weighted graph where each junction has a two-color periodic light and you may cross an edge only when both endpoint lights match.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Math, Implementation
- Solved
- No attempts yet
Problem
The city of Kenosha has roads, numbered , that connect junctions, numbered . No two roads connect the same pair of junctions, and no road connects a junction to itself. The integer travel time between junctions and is the same in both directions, so .
Each junction has a single traffic light that shows one of two colors, blue or purple. Each light alternates periodically: it stays blue for a fixed number of seconds, then purple for another fixed number of seconds, then repeats. You may set off down the road between two junctions only if, at the exact instant you leave one junction for the other, the lights at both junctions show the same color. The two lights do not have to stay the same color for the rest of the trip.
If a vehicle reaches a junction at the exact instant its light switches, the new color applies. Vehicles may wait at a junction as long as they like. For each junction you are given its blue duration , its purple duration , its initial color (B for blue or P for purple), and the remaining time before that initial color first changes.
Starting at time at a source junction , find the minimum time needed to reach a destination junction ().
Constraints: , , , , , , .
Worked example. Consider four junctions and five roads, where a vehicle wants to travel from junction 1 to junction 4.
Roads (with travel times): 1-2 (4), 1-3 (40), 2-3 (75), 2-4 (76), 3-4 (77).
The minimum time is 127, along the path 1 -> 2 -> 4:
- Junction 1 starts blue while junction 2 is purple, so the vehicle waits 2 seconds until junction 1 also turns purple, then drives 4 seconds to junction 2, arriving at time 6.
- At time 6 junction 2 turns blue, but junction 4 stays purple for 32 more seconds. After those 32 seconds junction 2 turns purple exactly as junction 4 turns blue, so they still differ. The vehicle waits 13 more seconds until junction 2 turns blue; now both are blue, so it drives 76 seconds to junction 4.
- Total time: seconds.
Input
- Line 1: two space-separated integers and .
- Line 2: two space-separated integers and .
- Lines 3 to : line describes junction with one character and three integers separated by single spaces: , , , and .
- Lines to : line describes road with three integers , , and .
Output
- Line 1: a single integer, the time of a minimum-time path from the source junction to the destination junction. If no path exists, output .