Limits 5s, 1.0 GB

You have a grid with n rows and m columns. Cell at the ii-th row and the jj-th column is called Cell(i,j)Cell(i, j) and id of the cell is G­i,jG­_{i,j}. Each cell has a unique id from 1 to n,m. You can jump from Cell(i,j)Cell(i,j) to Cell(x,y)Cell(x,y) by consuming power (ix)2+(jy)2(Gx,yGi,j){(i-x)^2+(j-y)^2}(G_{x,y}-G_{i,j}). In each day, you are going to select a number DD. In that day, you can jump DD cells, meaning if you are currently in a cell with id number pp, then in one jump, you can go to another cell which id is (p+D)(p+D). In the second jump you will be in (p+2D)(p+2D), then (p+3D)(p+3D) and so on. At kk-th day, you have to go from pp-th cell to qq-th cell. You can select different D for each day. Now, you want to minimize the total power consumption.

Input

Input starts with two integers nn and mm (1n,m3001 ≤ n, m ≤ 300).

Each of the next n lines contain mm integers representing the grid. Then the next line contains one integer QQ (1Q1051 ≤ Q ≤ 10^5), representing the number of days. The next QQ lines will have the information of each day. In each line, there will be two id pp and qq (1pqn×m1 ≤ p ≤ q ≤ n \times m).

Output

For each day, you have to output minimum power on a line by itself.

Sample

InputOutput
3 3
1 4 3
2 5 7
8 9 6
4
4 8
6 9
5 8
1 9
9
3
6
12

In the last day, you want to go from 1st cell to 9th. You can select 1, 2, 4, 8 as the candidate values for D for that day. Otherwise you can not go from 1st cell to 9th cell.

If you select 1 as D, you have to go through 1, 2, 3, 4, 5, 6, 7, 8, 9. The cost will be (12)2+(11)2(21)+(21)2+(13)2(32)+(11)2+(32)2(43)+(12)2+(22)2(54)+(23)2+(23)2(65)+(32)2+(33)2(76)+(23)2+(31)2(87)+(33)2+(12)2(98)=17{(1-2)^2+(1-1)^2}(2-1)+ {(2-1)^2+(1-3)^2}(3-2)+ {(1-1)^2+(3-2)^2}(4-3)+ {(1-2)^2+(2-2)^2}(5-4)+ {(2-3)^2+(2-3)^2}(6-5)+ {(3-2)^2+(3-3)^2}(7-6)+ {(2-3)^2+(3-1)^2}(8-7)+ {(3-3)^2+(1-2)^2}(9-8) = 17

If you select 2 as D, you have to go through 1, 3, 5, 7, 9. The cost will be (11)2+(13)2(31)+(12)2+(32)2(53)+(22)2+(23)2(75)+(23)2+(32)2(97)=18{(1-1)^2+(1-3)^2}(3-1)+ {(1-2)^2+(3-2)^2}(5-3)+ {(2-2)^2+(2-3)^2}(7-5)+ {(2-3)^2+(3-2)^2}(9-7) = 18.

If you select 4 as D, you have to go through 1,5,9. The cost will be (12)2+(12)2(51)+(23)2+(22)2(95)=12{(1-2)^2+(1-2)^2}(5-1)+ {(2-3)^2+(2-2)^2}(9-5) = 12.

If you select 8 as D, you have to go through 1,9. The cost will be (13)2+(12)2(91)=40{(1-3)^2+(1-2)^2}*(9-1) = 40

So, the minimum cost will be 12.


Submit

Login to submit.

Statistics

86% Solution Ratio
underdogEarliest, May '18
CodefresherFastest, 1.3s
AnachorLightest, 146 MB
NirjhorShortest, 1388B
Toph uses cookies. By continuing you agree to our Cookie Policy.