A freight yard is laid out on an infinite integer grid. A cart may walk directly between any two points (ax, ay) and (bx, by) at a cost equal to their Manhattan distance, |ax - bx| + |ay - by|, in any of the four axis directions, any number of times.
The yard also has k one-way conveyor belts. The i-th conveyor is described by five integers x1_i, y1_i, x2_i, y2_i, cost_i: stepping onto the conveyor at (x1_i, y1_i) carries the cart all the way to (x2_i, y2_i) for a flat fee of cost_i, regardless of how far apart those two points are and regardless of the Manhattan distance between them (a conveyor may in fact be a bad deal if its fee exceeds the Manhattan distance it spans, in which case simply walking past it is better). Conveyors only run in the stated direction; there is no belt running from (x2_i, y2_i) back to (x1_i, y1_i) unless a separate conveyor says so.
Given a start point (sx, sy) and a target point (tx, ty), find the minimum total cost for the cart to travel from the start to the target, using any combination of walking and riding conveyors (each conveyor may be used, skipped, or in principle ridden more than once, in whatever order gets the cart to the target most cheaply).
Line 1: four integers sx sy tx ty.
Line 2: one integer k, the number of conveyor belts.
Each of the next k lines: five integers x1 y1 x2 y2 cost describing one conveyor.
A single integer: the minimum total travel cost from (sx, sy) to (tx, ty).
1 <= sx, sy, tx, ty <= 10^50 <= k <= 2001 <= x1, y1, x2, y2 <= 10^5 for every conveyor1 <= cost <= 10^5 for every conveyorExample 1
Input
1 1 10 10 1 3 3 8 8 5
Expected
13
Explanation
Walking straight from (1,1) to (10,10) costs the Manhattan distance |1-10|+|1-10|=18. Instead, walk from (1,1) to the conveyor's entrance (3,3), costing |1-3|+|1-3|=4; ride the conveyor to (8,8) for its flat fee of 5; then walk from (8,8) to (10,10), costing |8-10|+|8-10|=4. Total = 4+5+4 = 13, which is cheaper than walking the whole way, and no other combination beats it.
Example 2
Input
2 3 7 9 0
Expected
11
Explanation
There are no conveyors (k=0), so the cart must walk the entire way, costing the Manhattan distance |2-7|+|3-9| = 5+6 = 11.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →