Under construction

Still being built. Things may change

Two-Dimensional Range Sum

Interview

Time limit1sMemory limit256 MB

Summary
Compute the sum of each queried rectangle in an N by N table using a 2D prefix sum.
Level

Medium4 of 10

Topics
Prefix sum, Matrix
Solved
No attempts yet

Problem

An N×NN \times N table is filled with N×NN \times N numbers. Write a program that computes the sum of the entries from (x1,y1)(x_1, y_1) to (x2,y2)(x_2, y_2). Here (x,y)(x, y) means row xx, column yy.

For example, take N=4N = 4 and the table below.

1234
2345
3456
4567

The sum from (2,2)(2, 2) to (3,4)(3, 4) is 3+4+5+4+5+6=273+4+5+4+5+6 = 27, and the sum from (4,4)(4, 4) to (4,4)(4, 4) is 77.

Given the numbers in the table and the sum queries, write a program that answers them.

Input

The first line contains the table size NN and the number of sums to compute, MM. (1≤N≤10241 \le N \le 1024, 1≤M≤1000001 \le M \le 100000)

Each of the next NN lines holds one row of the table, starting from row 1. A line lists the NN numbers of that row, starting from column 1. Every number in the table is a natural number no larger than 1,000.

Each of the next MM lines holds four integers x1x_1, y1y_1, x2x_2, y2y_2. (1≤x1≤x2≤N1 \le x_1 \le x_2 \le N, 1≤y1≤y2≤N1 \le y_1 \le y_2 \le N)

Output

Print MM lines. On each line print the sum from (x1,y1)(x_1, y_1) to (x2,y2)(x_2, y_2), one per query, in input order.

Examples2

  1. Example 1

    Input
    4 3
    1 2 3 4
    2 3 4 5
    3 4 5 6
    4 5 6 7
    2 2 3 4
    3 4 3 4
    1 1 4 4
    
    Expected output
    27
    6
    64
    
  2. Example 2

    Input
    2 4
    1 2
    3 4
    1 1 1 1
    1 2 1 2
    2 1 2 1
    2 2 2 2
    
    Expected output
    1
    2
    3
    4