题解 | #【模板】二维前缀和#
【模板】二维前缀和
https://www.nowcoder.com/practice/99eb8040d116414ea3296467ce81cbbc
先求矩阵和
#include <iostream> #include <vector> using namespace std; int main() { int n, m, q; cin >> n >> m >> q; vector<vector<long long>> A(n + 1, vector<long long>(m + 1)); A[0][0] = 0; for(int i = 0; i <= n; ++i) { A[i][0] = 0; } for(int j = 0; j <= m; ++j) A[0][j] = 0; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { long long num; cin >> num; // 先求矩阵和 A[i][j] += A[i - 1][j] + A[i][j - 1] - A[i - 1][j - 1] + num; // cout << A[i][j] << " "; } } while(q--) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; long long ans = A[x2][y2] - A[x2][y1 - 1] - A[x1 - 1][y2] + A[x1 - 1][y1 - 1]; cout << ans << endl; } return 0; }