前缀和——HDU - 1559

题目链接

用一个sum[i][j]表示前i行前j列所有元素之和

当i>=x&&j>=y时,我们可以在前i行前j列找到满足大小的矩阵

由于我们i和j是从小到大找,所以每次找以a[i][j]作为右下角的目标矩阵来作比较

这样就能不重不漏了

题目代码

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long LL;
const int maxn=1007;
int t,m,n,x,y;
int a[maxn][maxn],sum[maxn][maxn];
int main(){
    scanf("%d",&t);
    while(t--){
        memset(sum,0,sizeof(sum));
        scanf("%d%d%d%d",&n,&m,&x,&y);
        int maxx=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                scanf("%d",&a[i][j]);
                sum[i][j]=sum[i-1][j]+sum[i][j-1]+a[i][j]-sum[i-1][j-1];
                if(i>=x&&j>=y)maxx=max(maxx,sum[i][j]-sum[i-x][j]-sum[i][j-y]+sum[i-x][j-y]);
            }
        }
        printf("%d\n",maxx);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/helman/p/11366088.html