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 submatrix.
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 a matrix of integers.
The next q lines, each containing four integers x1, y1, x2, y2, represent a set of queries.
Output format There are
q lines in total, and each line outputs one query result.
Data range
1≤n,m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤The value of the elements 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
Sample output:
17
27
21
在这里插入代码片
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int a[N][N], s[N][N];
int main()
{
int n, m, q;
cin >> n >> m >> q;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
cin >> 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] - s[i-1][j-1] + a[i][j]; //计算前缀和
int x1, x2, y1, y2;
while(q--) {
cin >> x1 >> y1 >> x2 >> y2;
int sum = s[x2][y2] - s[x1-1][y2] - s[x2][y1-1] + s[x1-1][y1-1]; //计算子矩阵和
cout << sum << endl;
}
return 0;
}