BZOJ 2901(矩阵求和-数学题)

2901: 矩阵求和

Time Limit: 20 Sec   Memory Limit: 256 MB
Submit: 70   Solved: 15
[ Submit][ Status][ Discuss]

Description

给出两个n*n的矩阵,m次询问它们的积中给定子矩阵的数值和。
 

Input

第一行两个正整数n,m。
接下来n行,每行n个非负整数,表示第一个矩阵。
接下来n行,每行n个非负整数,表示第二个矩阵。
接下来m行,每行四个正整数a,b,c,d,表示询问第一个矩阵与第二个矩阵的积中,以第a行第b列与第c行第d列为顶点的子矩阵中的元素和。
 

Output

对每次询问,输出一行一个整数,表示该次询问的答案。
 

Sample Input

3 2
1 9 8
3 2 0
1 8 3
9 8 4
0 5 15
1 9 6
1 1 3 3
2 3 1 2

Sample Output

661
388

【数据规模和约定】
对30%的数据满足,n <= 100。
对100%的数据满足,n <= 2000,m <= 50000,输入数据中矩阵元素 < 100,a,b,c,d <= n。


把图画出来,算一下,合并同类项。

eg:2*2

a1*(b1+b2)+a2*(b3+b4)+a3*(b1+b2)+a4*(b3+b4)

=(a1+a3)(b1+b2)+(a2+a4)(b3+b4)

etc..

于是我们发现一个子矩阵的和=x区间每列一一乘与y区间每行之和

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<iostream>
using namespace std;
#define MAXN (2000+10)
#define MAXM (50000+10)
#define For(i,n) for(int i=1;i<=n;i++)
/*
#define read(x) { char c;\
while(scanf("%c",&c)&&(c>57||c<48));\
x=c-48;\
while(scanf("%c",&c)&&(c>=48&&c<=57)) x=x*10+c-48;\
}*/
#define read(x) scanf("%d",&x);
int n,m,a[MAXN][MAXN]={0},b[MAXN][MAXN]={0};
int x1,y1,x2,y2;
int main()
{
    read(n);read(m);
    For(i,n) For(j,n) {read(a[i][j]) a[i][j]+=a[i-1][j];}
    For(i,n) For(j,n) {read(b[i][j]) b[i][j]+=b[i][j-1];}
    For(i,m)
    {
        read(x1);read(y1);read(x2);read(y2);
        if (x1>x2) swap(x1,x2);
		if (y1>y2) swap(y1,y2);
        long long ans=0;
        For(i,n) ans+=(long long)(a[x2][i]-a[x1-1][i])*(long long)(b[i][y2]-b[i][y1-1]);
		printf("%lld\n",ans);
    }
    return 0;
}



你可能感兴趣的:(BZOJ 2901(矩阵求和-数学题))