思路:
先写出式子:
展开得:
去括号得:
分别用三个二维前缀和算出 、 和 再套公式即可。
AC 代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 2e3 + 10;
int t, n, q;
ll s[N][N], si[N][N], sj[N][N];
int main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> t;
while(t--){
cin >> n >> q;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
int x;
cin >> x;
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x;
si[i][j] = si[i - 1][j] + si[i][j - 1] - si[i - 1][j - 1] + x * i;
sj[i][j] = sj[i - 1][j] + sj[i][j - 1] - sj[i - 1][j - 1] + x * j;
}
}
while(q--){
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
ll s1 = s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1];
ll s2 = si[x2][y2] - si[x2][y1 - 1] - si[x1 - 1][y2] + si[x1 - 1][y1 - 1];
ll s3 = sj[x2][y2] - sj[x2][y1 - 1] - sj[x1 - 1][y2] + sj[x1 - 1][y1 - 1];
s2 *= (y2 - y1 + 1);
s1 *= (x1 * (y2 - y1 + 1) + y1 - 1);
cout << s2 + s3 - s1 << ' ';
}
cout << '\n';
}
return 0;
}