区间Dp 暴力枚举+动态规划 Hdu1081

F - 最大子矩形
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u
Submit

Status
Description
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.
Input
The input consists of an N * 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

<span style="color:#3333ff;">/*
_________________________________________________________________________________________________________________
       author      :       Grant Yuan
       time        :       2014.7.19
       source      :       Hdu1081
       algorithm   :       暴力枚举+动态规划
       explain     :       暴力枚举第k1行到第k2行每一列各个元素的和sum[i],然后对sum[i]进行一次最大子序列求和
___________________________________________________________________________________________________________________
*/

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<functional>
#include<algorithm>
using namespace std;

int a[105][105];
int l;
int sum[105];
int dp[105];

int main()
{
	while(~scanf("%d",&l)){
		for(int i=0;i<l;i++)
			for(int j=0;j<l;j++)
			 scanf("%d",&a[i][j]);

		int ans=-9999999,ans1;
		for(int k1=0;k1<l;k1++)
			for(int k2=0;k2<l;k2++){
		   memset(dp,0,sizeof(dp));
		   memset(sum,0,sizeof(sum));
		 for(int i=0;i<l;i++){
			for(int j=k1;j<=k2;j++)
		     {
			   sum[i]+=a[i][j];
		         }
		   for(int m=0;m<l;m++)
		     {
		   	  dp[m+1]=max(dp[m]+sum[m],sum[m]);
		      }
		   ans1=dp[1];
		   for(int d=1;d<=l;d++)
			  if(dp[d]>ans1)
		ans1=dp[d];
		if(ans1>ans)
		      ans=ans1;}}

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

}
</span>

posted @ 2014-08-18 21:08  mengfanrong  阅读(287)  评论(0编辑  收藏  举报