题解 | #【模板】二维前缀和#
【模板】二维前缀和
https://www.nowcoder.com/practice/99eb8040d116414ea3296467ce81cbbc
#include <iostream> #include <vector> using namespace std; int main() { int n = 0, m = 0, q = 0; cin >> n >> m >> q; vector<vector<long long>> nums(n+1, vector<long long>(m+1)); for (int i = 1; i < n + 1; ++i) { for (int j = 1; j < m + 1; ++j) { cin >> nums[i][j]; } } // 创建前缀和矩阵 vector<vector<long long>> dp(n + 1, vector<long long>(m + 1)); for (int i = 1; i < n + 1; ++i) { for (int j = 1; j < m + 1; ++j) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + nums[i][j] - dp[i - 1][j - 1]; } } // 使用前缀和矩阵 while (q--) { int x1 = 0, y1 = 0, x2 = 0, y2 = 0; cin >> x1 >> y1 >> x2 >> y2; cout << (dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1 - 1][y1 - 1]) << endl; } return 0; } // 64 位输出请用 printf("%lld")