题目地址:
https://www.acwing.com/problem/content/798/
给定一个 n n n行 m m m列的整数矩阵 A A A,和 q q q次询问,每次询问包含四个整数 x 1 , y 1 , x 2 , y 2 x_1,y_1,x_2,y_2 x1,y1,x2,y2,表示一个子矩阵左上角和右下角的坐标。求这个子矩阵的和。坐标是从 1 1 1开始计数的。
思路是用前缀和。先求出前缀和矩阵 s s s,递推公式为: s [ i + 1 ] [ j + 1 ] = A [ i ] [ j ] + s [ i + 1 ] [ j ] + s [ i ] [ j + 1 ] − s [ i ] [ j ] s[i+1][j+1]=A[i][j]+s[i+1][j]+s[i][j+1]-s[i][j] s[i+1][j+1]=A[i][j]+s[i+1][j]+s[i][j+1]−s[i][j]针对每次询问,子矩阵和为: 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]代码如下:
#include <iostream>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N], s[N][N];
int main() {
cin >> n >> m >> q;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &a[i][j]);
// 求前缀和矩阵
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
s[i + 1][j + 1] = a[i][j] + s[i][j + 1] + s[i + 1][j] - s[i][j];
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;
}
预处理时间复杂度 O ( n m ) O(nm) O(nm),每次询问时间 O ( 1 ) O(1) O(1),空间 O ( n m ) O(nm) O(nm)。