使用二维前缀和即可,需要注意不定长的二维数组可以使用vector
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 1005; int __t = 1, n, m, q, x11, y11, x2, y2; void solve() { cin >> n >> m >> q; vector<vector<int>> a(n + 1, vector<int>(m + 1, 0)), sum(n + 1, vector<int>(m + 1, 0)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; sum[i][j] = a[i][j] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } while (q--) { cin >> x11 >> y11 >> x2 >> y2; int ans = sum[x2][y2] - sum[x11 - 1][y2] - sum[x2][y11 - 1] + sum[x11 - 1][y11 - 1]; cout << ans << '\n'; } } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }