Under construction

Still being built. Things may change

The Legend of Dakgangjeong

Interview

Time limit4sMemory limit512 MB

Summary
Given an N by N grid, answer Q rectangle queries by summing interior cells as +1 and border cells as -1.
Level

Easy3 of 10

Topics
Prefix sum, Matrix
Solved
No attempts yet

Problem

Arim lives in Changwon and is a 'beer-only drinker', so beer never makes Arim drunk. Boseon is a 'soju-only drinker' and is sure that drinking beer with Arim would leave Boseon completely drunk. So Boseon decided to trust the legend of the chicken near the Gyeongsang National University back gate.

According to the legend, a special fried chicken sold near the back gate of Gyeongsang National University has a certain level of intoxication-blocking power. Boseon went to that shop. Its sales system is unlike that of an ordinary chicken shop.

The system works as follows.

  • There is an N×NN \times N grid, and each cell holds 1 g of boneless chicken.
  • The chicken in row ii, column jj has a constant ki,jk_{i,j}.
  • A buyer picks two points (r1,c1)(r_1, c_1) and (r2,c2)(r_2, c_2). After the two points are chosen, all chicken in every cell (r,c)(r, c) with r1≤r≤r2r_1 \le r \le r_2 and c1≤c≤c2c_1 \le c \le c_2 is packed together and fried.
  • The intoxication-blocking level of the fried chicken is computed as follows.

∑i=r1r2∑j=c1c2ki,j×{1if r1<i<r2 and c1<j<c2−1otherwise\sum_{i=r_1}^{r_2} \sum_{j=c_1}^{c_2} k_{i,j} \times \begin{cases} 1 & \text{if } r_1 < i < r_2 \text{ and } c_1 < j < c_2 \\ -1 & \text{otherwise} \end{cases}

The machine that calculates this for each pair of points broke down on the day Boseon visited. Boseon asked the people nearby to compute the level for every pair of points chosen.

Let's help Boseon.

Input

The first line contains the grid size NN. (5≤N≤5 0005 \le N \le 5\,000)

From the second line onward, the next NN lines each contain NN space-separated values, where the jj-th value on the ii-th line is the constant ki,jk_{i,j}. (1≤ki,j≤101 \le k_{i,j} \le 10)

The line N+2N+2 contains the number of queries QQ. (1≤Q≤100 0001 \le Q \le 100\,000)

From line N+3N+3 onward, the next QQ lines each contain r1r_1, c1c_1, r2r_2, c2c_2, separated by spaces. (1≤r1,c1,r2,c2≤N1 \le r_1, c_1, r_2, c_2 \le N; r1+2≤r2r_1 + 2 \le r_2; c1+2≤c2c_1 + 2 \le c_2)

All numbers in the input are integers.

Output

For each of the QQ queries, print on its own line the intoxication-blocking level of the fried chicken chosen by r1r_1, c1c_1, r2r_2, c2c_2.

Hint

Python 3 users are recommended to submit with PyPy3.

Examples1

  1. Example 1

    Input
    5
    1 1 1 1 1
    1 2 2 2 1
    1 2 3 2 1
    1 2 2 2 1
    1 1 1 1 1
    2
    1 1 5 5
    2 2 4 4
    
    Expected output
    3
    -13