POJ 1050 to the max

原题:

Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.

As an example, the maximal sub-rectangle of the array:

0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:

9 2
-4 1
-1 8

and has a sum of 15.

求出矩形中的最小和。

我们不难发现二维的数表令人非常头疼,甚至连暴力枚举所有长方形的算法都难以写出。(而且比较次数会很恐怖)。此时我们应该考虑如何能把维数降下来。一般而言,如果单对行枚举,会减少一维。于是我们把多行作一捆绑,就只剩下列了,转化成经典的最大连续和问题。

源代码:

#include <iostream>
#include <memory.h>
#include<stdio.h>
using namespace std;


int main()
{
    int n;
    cin>>n;
    int max=-10000,thissum,maxsum;
    int a[501][501];
    int save[n];
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            scanf("%d",&a[i][j]);
    for(int i=0;i<n;i++)
    {    memset(save,0,sizeof(save));
        for(int j=i;j<n;j++)
        {
            thissum=0,maxsum=0;


            for(int k=0;k<n;k++)
            {


                save[k]+=a[j][k];//此处j自然利用,千万别加多余的循环。
            }
            for(int x=0;x<n;x++)
            {
                thissum+=save[x];
                if(thissum>maxsum)maxsum=thissum;
                else if(thissum<0)thissum=0;
            }
            max=max<maxsum?maxsum:max;
        }
    }
    cout<<max<<endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值