【上交OJ】1002:二哥种花生(二维前缀和+二维差分---模版题)

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/88667948

题目地址:https://acm.sjtu.edu.cn/OnlineJudge/problem/1002

Description


二哥在自己的后花园里种了一些花生,也快到了收获的时候了。这片花生地是一个长度为L、宽度为W的矩形,每个单位面积上花生产量都是独立的。他想知道,对于某个指定的区域大小,在这么大的矩形区域内,花生的产量最大会是多少。

Input Format

第1行有2个整数,长度L和宽度W。

第2行至第L+1行,每行有W个整数,分别表示对应的单位面积上的花生产量A( 0≤A<100≤A<10 )。

第L+2行有2个整数,分别是指定的区域大小的长度a和宽度b。

Output Format

输出一个整数m,表示在指定大小的区域内,花生最大产量为m。

Sample Input

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

Sample Output

38

样例解释

左上角:38 = (1+2+3) + (6+7+8) + (0+9+2)

数据范围

对于30%的数据: 1≤L,W≤1001≤L,W≤100;

对于100%的数据: 1≤L,W≤10001≤L,W≤1000。

全部区域大小满足:1≤a≤L,1≤b≤W1≤a≤L,1≤b≤W 。

解题思路:


二维前缀和和二维差分模版题具体模版见:

ac代码:


#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#define maxn 1005
using namespace std;
typedef long long ll;
int s[maxn][maxn]={0};
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    int ans=-1,l,w,a,b,x;
    scanf("%d %d",&l,&w);
    for(int i=1;i<=l;i++)
    {
        for(int j=1;j<=w;j++)
        {
            scanf("%d",&s[i][j]);
            s[i][j]+=s[i-1][j]+s[i][j-1]-s[i-1][j-1];
        }
    }
    scanf("%d %d",&a,&b);
    for(int i=1;i+a-1<=l;i++)
    {
        for(int j=1;j+b-1<=w;j++)
        {

            x=s[a+i-1][b+j-1]-s[i-1][b+j-1]-s[a+i-1][j-1]+s[i-1][j-1];
            ans=max(ans,x);

        }
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/88667948