Linearville
Time limit1sMemory limit1024 MB
For each query, find the length of a shortest path between two grid crossings when the path must alternate directions at every crossing.
- Level
Hard8 of 10
- Topics
- Shortest path, Graph, Prefix sum, Dynamic programming
- Solved
- No attempts yet
Problem

Linearville has two way streets running west to east and two way streets running south to north. Together they form a grid of blocks. The distance between two consecutive parallel streets is 1 or 5.
The Linearville Transit Authority is running an experiment and now requires every car to change direction at every crossing it passes. A car that reaches a crossing must turn left or right, so it can never drive straight through a crossing, and the segments of its path alternate between the west to east direction and the south to north direction. A path that obeys this rule is an alternating path. Each segment of a path joins two crossings that are consecutive on the same street, and the length of the path is the sum of the distances of its segments. The car has no previous move at the start crossing, so the first segment may run in either direction.
The figure shows an alternating path on a grid with . That path is not a shortest alternating path.
The authority is building a new navigation app. Given pairs of a start crossing and a target crossing, write a program that computes the length of a shortest alternating path for each pair. Linearville may be huge.
Input
The first line contains an integer (), the number of streets in each direction. In each direction the streets carry distinct numbers from to , starting at the south west corner of the city.
The second line contains the integers (), where is the distance between the south to north street and the south to north street .
The third line contains the integers (), where is the distance between the west to east street and the west to east street .
The fourth line contains an integer (), the number of queries.
Each of the next lines contains four integers , , , (). The start crossing is and the target crossing is . and are south to north streets, while and are west to east streets. No query appears twice.
Output
Print lines. Line contains one integer, the length of a shortest alternating path for query . If the start crossing and the target crossing are the same, print 0.