2D prefix sum submatrix

2D prefix sum submatrix

 How to calculate prefix and matrix:

        _{^{^{^{^{}}}}}S_{xy}=S_{x-1y}+S_{xy-1} -S_{s-1y-1}+a_{xy}

How to use the prefix sum matrix to calculate the sum of a certain submatrix:

        Such as seeking: [x1y1, x2, y2] sub-matrix sum, Sx2, y2-Sx2, y-1-Sx1-1, y2+Sx1-1, y1-1

Examples and code templates:

sum of submatrices

Input an integer matrix with n rows and m columns, and then input q queries, each query contains four integers x1, y1, x2, y2, representing 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 submatrix.

Input format
The first line contains three integers n, m, q.

The next n lines, each containing m integers, represent an integer matrix.

Next q lines, each line contains four integers x1, y1, x2, y2, representing a set of queries.

Output format
There are q lines in total, 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≤value of elements in the matrix≤1000

Input sample:

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

Sample output:

17
27
21
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1007;
int n,m,q;
int a[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]);
			a[i][j]=a[i-1][j]+a[i][j-1]+a[i][j]-a[i-1][j-1]; 
		}
	}
	while(q--){
		int x1,x2,y1,y2;
		scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
		printf("%d\n",a[x2][y2]-a[x2][y1-1]-a[x1-1][y2]+a[x1-1][y1-1]);
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/m0_56501550/article/details/129843708