HDU - 6336 - Problem E. Matrix from Arrays
题意:
按照题中所给代码构造一个无限的矩阵,求左上角为(x1,y1),右下角为(x2,y2)的子矩阵的权值和。
int cursor = 0;
for (int i = 0; ; ++i) {
for (int j = 0; j <= i; ++j) {
M[j][i - j] = A[cursor];
cursor = (cursor + 1) % L;
}
}
可以发现每一个 i 都是表示赋值点到(0,0)的曼哈顿距离,然后就可以得到M[i][j] = A[((i+j)*(i+j+1)/2+i)%L]
然后循环节就是2L,每个子矩阵都可以分为多个(2L*2L)的矩阵和几个较小的矩阵
可以先求出2L*2L矩阵的前缀和,然后就可以很快得到所有的小矩阵的和。
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef long long int LL;
const int N = 111;
LL T, L, Q, a[N];
LL dx, dy, mod;
LL sum[N][N];
LL f(LL x1, LL y1, LL x2, LL y2) {
if(x1 > x2 || y1 > y2) return 0;
LL ans = sum[x2][y2];
if(x1) ans -= sum[x1-1][y2];
if(y1) ans -= sum[x2][y1-1];
if(x1 && y1) ans += sum[x1-1][y1-1];
return ans;
}
LL fx(LL x1, LL y1, LL x2, LL y2){ // x 溢出
y1 %= mod; y2 %= mod;
LL ans = f(0, y1, x2%mod, y2);
LL t = (x2-x1-dx) / mod;
ans += t * f(0, y1, mod-1, y2);
if(x1%mod) ans += f(x1%mod, y1, mod-1, y2);
return ans;
}
LL fy(LL x1, LL y1, LL x2, LL y2){ // y 溢出
x1 %= mod; x2 %= mod;
LL ans = f(x1, 0, x2, y2%mod);
LL t = (y2-y1-dy) / mod;
ans += t * f(x1, 0, x2, mod-1);
if(y1%mod) ans += f(x1, y1%mod, x2, mod-1);
return ans;
}
int main()
{
scanf("%lld", &T);
while(T--){
scanf("%lld", &L);
for(int i=0;i<L;i++) scanf("%lld", &a[i]);
for(int i=0;i<2*L;i++){
for(int j=0;j<2*L;j++){
sum[i][j] = a[((i+j)*(i+j+1)/2+i)%L];
if(i) sum[i][j] += sum[i-1][j];
if(j) sum[i][j] += sum[i][j-1];
if(i && j) sum[i][j] -= sum[i-1][j-1];
}
}
mod = 2*L;
scanf("%lld", &Q);
while(Q--){
LL ans = 0, x1, x2, y1, y2;
scanf("%lld%lld%lld%lld", &x1, &y1, &x2, &y2);
dx = x2 % mod; dy = y2 % mod;
if(y1+dy >= y2) {
if(x1+dx >= x2) { // 含于
x1 %= mod; x2 %= mod; y1 %= mod; y2 %= mod;
ans = f(x1, y1, x2, y2);
} else { // 横坐标溢出
ans = fx(x1, y1, x2, y2);
}
} else { // 纵坐标溢出
if(x1+dx >= x2) {
ans = fy(x1, y1, x2, y2);
} else { // 横坐标溢出
ans = fy(x2-dx, y1, x2, y2);
LL t = (x2 - dx - x1) / mod;
ans += t * fy(0, y1, mod-1, y2);
if(x1%mod) ans += fy(x1%mod, y1, mod-1, y2);
}
}
printf("%lld\n", ans);
}
}
return 0;
}