Journey through the kingdom
Time limit3sMemory limit256 MB
Find the cheapest carriage-hopping cost between consecutive target cells on a grid where each cell rents a ride to any cell in its rectangle range.
- Level
Hard8 of 10
- Topics
- Shortest path, Segment tree
- Solved
- No attempts yet
Problem
The kingdom of Quadradonia is divided into provinces arranged in a grid of rows and columns. The roads between them are dangerous, so nobody travels alone. Every trip goes by escorted carriage, and the carriages belong to the Interprovincial Communication and Peregrination Company (ICPC).
The company charges like this. In the province in row and column you rent a carriage for a cost of . That carriage takes you to any province at most rows away from row and at most columns away from column , that is, to the province in row and column whenever and . The price is flat: it depends on the province where you rent, not on where you get off.
You want to visit provinces in that order. Your budget is small, so for every leg of the trip you want the cheapest way to make it. A leg may pass through any number of intermediate provinces, and you pay the rental cost of every province where you board a carriage.
Input
The first line contains three integers , and (, ), the number of rows, the number of columns and the number of provinces you want to visit. Rows are numbered from 1 to and columns from 1 to .
The next lines form three groups of lines, each line holding integers. The -th number on the -th line of the first group is (). The second group gives () in the same layout, and the third group gives ().
The last lines describe in visiting order. The -th of them contains two integers and (, ), meaning that is the province in row and column .
Output
Print one line with integers separated by single spaces. For , the -th number is the minimum total rental cost of going from to with the escorted carriage system, or if that leg is impossible. If and are the same province the cost is 0.