用
s
[
i
,
j
]
s[i, j]
s[i,j]记录矩阵左上角(包括自身)所有的元素和。
例如
s
[
2
,
3
]
=
a
[
1
,
1
]
+
a
[
1
,
2
]
+
a
[
1
,
3
]
+
a
[
2
,
1
]
+
a
[
2
,
2
]
+
a
[
2
,
3
]
s[2, 3] = a[1, 1] + a[1, 2] + a[1, 3] + a[2, 1] + a[2, 2] + a[2, 3]
s[2,3]=a[1,1]+a[1,2]+a[1,3]+a[2,1]+a[2,2]+a[2,3]
要求左上角是 [ x 1 , y 1 ] [x_1, y_1] [x1,y1],右下角是 [ x 2 , y 2 ] [x_2, y_2] [x2,y2]的矩阵元素的和,只需 s [ x 2 , y 2 ] − s [ x 2 , y 1 − 1 ] − s [ x 1 − 1 , y 2 ] + s [ x 1 − 1 , y 1 − 1 ] s[x_2, y_2] - s[x_2, y_1-1]- s[x_1 - 1, y_2] + s[x_1-1, y_1 - 1] s[x2,y2]−s[x2,y1−1]−s[x1−1,y2]+s[x1−1,y1−1]
求s的过程同理
s
[
i
,
j
]
=
a
[
i
,
j
]
+
s
[
i
−
1
,
j
]
+
s
[
i
,
j
−
1
]
−
s
[
i
−
1
,
j
−
1
]
s[i, j] = a[i, j] + s[i-1, j]+s[i, j-1]-s[i-1, j-1]
s[i,j]=a[i,j]+s[i−1,j]+s[i,j−1]−s[i−1,j−1]
#include <iostream>
using namespace std;
const int N = 1005;
int n, m, q, s[N][N];
int main() {
int a;
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i ++ ) {
for (int j = 1; j <= m; j ++ ) {
scanf("%d", &a);
s[i][j] += a + s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
}
}
int x1, y1, x2, y2;
for (int i = 1; i <= q; i ++ ) {
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
printf("%d\n", s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
}
return 0;
}