题目:
题解:
这种前缀和和一次的类似:
看上面这个图中,黑色部分的和,即为:
红色和-绿色和-黄色和+紫色和
即为:sum[x2][y2] - sum[x2][y1-1] - sum[x1-1][y2] + sum[x1-1][y1-1];
求每个位置的和也是按照这个方式:
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + s[i][j];
然后求哪个部分面积,就讲哪个部分的和相减:
代码:
#include<iostream>
using namespace std;
const int N = 10010;
int s[N][N], sum[N][N] = {0};
int n, m, q;
int main()
{
scanf_s("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf_s("%d", &s[i][j]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + s[i][j];
}
int x1, y1, x2, y2;
while (q--)
{
scanf_s("%d%d%d%d", &x1, &y1,&x2,&y2);
cout << sum[x2][y2] - sum[x2][y1-1] - sum[x1-1][y2] + sum[x1-1][y1-1] << endl;
}
system("pause");
}