解法一、二維前綴和
✅ 完整代碼
評分結果(參考) : AC (0.1s, 724KB)
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, temp;
while(cin >> n >> m){
vector<vector<int>> presum(n+1, vector<int>(n+1));
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin >> temp;
presum[i][j] = presum[i-1][j] + presum[i][j-1] - presum[i-1][j-1] + temp;
}
}
for(int i=0; i<m; i++){
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << presum[x2][y2] - presum[x1-1][y2] - presum[x2][y1-1] + presum[x1-1][y1-1] << "\n";
}
}
return 0;
}