HDU 1081 To The Max (DP)

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

4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
 

Sample Output

15
 

这道题是求大矩阵中小矩形的和的最大值


可以先算出num[i][j]代表第i行前面j列的值
然后相当于固定一列i,j从1~i中变化,K代表行从1~n开始循环,相当于能求出固定两行之间
的矩形的最大值(当然也可以看成求子序列的最大值了,因为每行可以的和可以看成一个数,就相当于压缩成了一维)
每次找到最大值更新结果就可以了

一维的最大连续子序列的递推公式:

f[i]=max{f[i-1]+a[i],a[i]}  (以a[i]结尾的最大连续子序列)

 

 1 #include<stdio.h>

 2 #include<string.h>

 3 #include<stdlib.h>

 4 #include<algorithm>

 5 using namespace std;

 6 int num[101][101];

 7 int ans;

 8 int main()

 9 {

10     int n,i,j,k,a;

11     while(scanf("%d",&n)!=EOF)

12     {

13         memset(num,0,sizeof(num));

14         for(i=1;i<=n;i++){

15             for(j=1;j<=n;j++){

16                 scanf("%d",&a);

17                 num[i][j]=num[i][j-1]+a;

18             }

19         }

20         int maxn=-0x3fffffff;

21         for(i=1;i<=n;i++)

22         {

23             for(j=1;j<=i;j++)

24             {

25                 ans=-1;

26                 for(k=1;k<=n;k++)

27                 {

28                     if(ans>0)

29                     ans+=num[k][i]-num[k][j-1];

30                     else

31                     ans=num[k][i]-num[k][j-1];

32                     if(ans>maxn)

33                         maxn=ans;

34                 }

35             }

36         }

37         printf("%d\n",maxn);

38     }

39     return 0;

40 }
View Code

 

 

你可能感兴趣的:(HDU)