HDU 1081 To The Max【DP】【最大子段矩阵求和】

来源:互联网 发布:杭州创业软件招聘 编辑:程序博客网 时间:2024/06/02 20:50
D - To The Max
Crawling in process...Crawling failedTime Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u
SubmitStatusPracticeHDU 1081

Description

Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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. 

Input

The input consists of an N x N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N 2 integers separated by whitespace (spaces and newlines). These are the N 2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127]. 

Output

Output the sum of the maximal sub-rectangle. 

Sample Input

40 -2 -7 0 9 2 -6 2-4 1 -4 1 -18 0 -2

Sample Output

15  

注意:

1:由一维数组最大子段和求解方法引申到二位矩阵最大  

一维数组最大子段和最大的方法是 temp[i]=(temp[i-1]>0?temp[i-1]:0)+a[i];

二维压缩成一维数组后 再找出最大组合

/*一道DP题目二维数组压缩*/#include<stdio.h>#include<string.h>int max(int n,int a[])//一维数组最大子段和求解方法{    int temp[133];    int max=n*(-127);    memset(temp,0,sizeof(temp));    for(int i=1; i<=n; i++)    {        temp[i]=(temp[i-1]>0?temp[i-1]:0)+a[i];        if(max<temp[i])        {            max=temp[i];        }    }    return max;}int main (void){    int sum, n,a[130][130],b[130];    while(~scanf("%d",&n)&&n)    {        int sum=n*(-127);        memset(a,0,sizeof(a));        for(int i=1; i<=n; i++)        {            for(int ii=1; ii<=n; ii++)            {                scanf("%d",&a[i][ii]);//输入            }        }        for(int i=1; i<=n; i++)//从第一行开始        {            for(int ii=1; ii<=n; ii++)//每次更新i. b[]刷新            {                b[ii]=0;            }            for(int j=i; j<=n; j++)            {                for(int jj=1; jj<=n; jj++)                {                    b[jj]+=a[j][jj];//表示从第i行到第n行中第k列的总和。                    //这两句放在这里有问题 WA                    //int maxs=max(n,b);                    //if(maxs>sum) sum=maxs;                }                int maxs=max(n,b);                if(maxs>sum) sum=maxs;            }        }        printf("%d\n",sum);    }    return 0;}



0 0
原创粉丝点击