HDU 1081 to the max 基础DP 好题

                  To The Max



Problem 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
 
 
 
 
 
就是给一个n*n的矩阵,求出它的最大子矩阵
 
我们都做过求一个序列的最大子序列吧。O(n)的复杂度。
 
这道题就是那道题转化一下。
 
暴力枚举第k1行到第k2行每一列各个元素的和sum[i],然后对sum[i]进行一次最大子序列求和
 
然后不断更新答案
 
 
 
HDU 1081 to the max 基础DP 好题
 1 #include<cstdio>

 2 #include<cstring>

 3 #include<algorithm>

 4 

 5 using namespace std;

 6 

 7 const int maxn=105;

 8 

 9 int a[maxn][maxn];

10 int sum[maxn];

11 int dp[maxn];

12 

13 int main()

14 {

15     int n;

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

17     {

18         for(int i=1;i<=n;i++)

19             for(int j=1;j<=n;j++)

20                 scanf("%d",&a[i][j]);

21 

22         int ans=-1000000;

23 

24         for(int i=1;i<=n;i++)

25         {

26             memset(dp,0,sizeof(dp));

27             memset(sum,0,sizeof(sum));

28             for(int j=i;j<=n;j++)

29             {

30                 for(int k=1;k<=n;k++)

31                 {

32                     sum[k]+=a[j][k];

33                 }

34 

35                 for(int k=1;k<=n;k++)

36                 {

37                     dp[k]=max(dp[k-1],0)+sum[k];

38                     if(dp[k]>ans)

39                         ans=dp[k];

40                 }

41 

42             }

43         }

44 

45         printf("%d\n",ans);

46     }

47 

48     return 0;

49 }
View Code

 

 
 
 
 
 
 
 
 
 

你可能感兴趣的:(HDU)