Ship Journey
Time limit1sMemory limit128 MB
Find the latest whole-minute departure so the ship reaches 100 km strictly before the deadline, minimizing travel time.
- Level
Medium5 of 10
- Topics
- Simulation, Brute force, Prefix sum
- Solved
- No attempts yet
Problem
Captain Hansen wants to sail his small barge down the river Elbe, from Hamburg to Cuxhaven. During the trip he must account for the tide. When the tide is falling, the water flows toward the North Sea and speeds the ship up; when the tide is rising, the drift works against the ship and slows it down. The drift is not constant — its speed and direction change over time.
The distance from Hamburg to Cuxhaven is km. Through the water the ship always moves at a constant km/h (ignoring drift). Its real speed over ground is that speed plus the drift: , where is the current drift in km/h. A positive means drift from Hamburg toward Cuxhaven (which speeds the ship up); a negative means drift in the opposite direction (which slows it down). Because the drift never exceeds the ship's own speed (), the real speed is never negative — at worst the ship stands still. At any given moment the drift is the same everywhere on the river, and it changes at most once per minute, staying constant until the next change.
Hansen runs a just-in-time service, so he wants to leave as late as he safely can. Determine the optimal whole-minute departure time (measured in minutes from midnight). The optimal departure satisfies, in order:
- Departing at guarantees arrival at Cuxhaven strictly before the deadline.
- Among all such departures, the journey takes the least possible time.
- If several departures achieve that minimal journey time, choose the latest one.
Input
The first line contains the number of scenarios .
Each scenario is given as follows:
- A line with the deadline — the latest allowed arrival time, in minutes from midnight ().
- A line with the number of drift data sets ().
- lines, each of the form
m swith two integers (, ). From minute onward the drift speed and direction are km/h, and this value holds until the next data set. A positive is drift from Hamburg toward Cuxhaven; a negative is drift in the opposite direction.
Times are in minutes, speeds in km/h, distances in km. The first data set of every scenario is for minute . You may assume a valid departure always exists — leaving at midnight already meets the deadline.
Output
For each scenario, print a single line with the optimal departure time (a whole number of minutes from midnight).