Two-dimensional prefix sum
topic
Enter an integer matrix with n rows and m columns, and then enter q queries. Each query contains four integers x1, y1, x2, y2, which represent the coordinates of the upper left corner and the lower right corner of a sub-matrix.
For each query, output the sum of all numbers in the sub-matrix.
Input format The
first line contains three integers n, m, q.
The next n rows, each row contains m integers, representing a matrix of integers.
Next line q, each line contains four integers x1, y1, x2, y2, representing a set of queries.
Output format There are
q lines, and each line outputs a query result.
Data range
1≤n, m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤The value of the element in the matrix≤1000
Input example:
3 4 3
1 7 2 4
3 6 2 8
2 1 2 3
1 1 2 2
2 1 3 4
1 3 3 4
Output example:
17
27
21
Two-dimensional prefix and derivation
As shown:
The purple area refers (1,1)
to (i,j-1)
the rectangular area from the upper left corner to the lower right corner, and the green area refers (1,1)
to (i-1, j )
the rectangular area from the upper left corner to the lower right corner. The area of each color rectangle represents the sum of its surrounding elements.
From the figure, we can easily see that the area of the entire outer blue rectangle s[i][j]
= green area s[i-1][j]
+ purple area s[i][j-1]
-repeated red area s[i-1][j-1]
+ small square area a[i][j]
;
Therefore, the two-dimensional prefix and preprocessing formula
s[i] [j] = s[i-1][j] + s[i][j-1 ] + a[i] [j] - s[i-1][ j-1]
Next regression to seek to (x1,y1)
the upper left corner and to the (x2,y2)
elements of the matrix and the lower right corner.
As shown:
Purple area refers to the ( 1,1 )
upper left corner of the (x1-1,y2)
rectangular area in the lower right corner, the yellow area refers to the (1,1)
upper left corner of the (x2,y1-1)
rectangular area of the lower right corner;
Not difficult to launch:
The area of the green rectangle = the entire outer area s[x2, y2]
-the yellow area s[x2, y1 - 1]
-the purple area s[x1 - 1, y2]
+ the red area repeatedly subtracteds[x1 - 1, y1 - 1]
So the conclusion of the two-dimensional prefix sum is:
To (x1, y1)
the upper left corner, (x2, y2)
for the child and for the lower right corner of the matrix:
s[x2, y2] - s[x1 - 1, y2] - s[x2, y1 - 1] + s[x1 - 1, y1 - 1]
to sum up:
Summary of personal experience of prefix sum and difference
Code:
#include<iostream>
#include<cstdio>
using namespace std;
const int N=1010;
int n,m,q;
int a[N][N],s[N][N];
int main()
{
scanf("%d %d %d",&n,&m,&q);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
s[i][j]=s[i-1][j]+s[i][j-1]+a[i][j]-s[i-1][j-1]; //求前缀和
}
}
while(q--)
{
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
printf("%d\n",s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1]);
}
return 0;
}