您的位置:首页 > 其它

POJ 1050 To the Max (动态规划——求最大子矩阵和)

2010-01-20 03:17 477 查看
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

#include<iostream>

using namespace std;

int main()
{
int arr[110][110],arr2[110],dp[110],n,max;
memset(arr,0,sizeof(arr));
while(cin >> n)
{
max = -2147483647;
for(int i = 1;i <= n;++i)
for(int j = 1;j <= n;++j)
cin >> arr[i][j];

//动态规划过程,将二维数组的和加起来,转化为一维,再利用求最大连续子序列的方法DP求之
for(int i = 1;i <= n; ++i)
{
memset(arr2,0,sizeof(arr2));
for(int j = i; j <= n; ++j)		//将矩阵从第i行加到第n行,每加一次算一次最大连续子序列一次
{
memset(dp,0,sizeof(dp));//初始化DP很重要
for(int x = 1;x <= n; ++x)
{
arr2[x] += arr[j][x];
if(dp[x - 1] + arr2[x] > 0)		//最大连续子段和的动态转移方程:
{								//DP(i) = 0				  if(DP(i-1) + F(i) < 0)
dp[x] = dp[x - 1] + arr2[x];//       = DP(i - 1) + F(i)   if(DP(i-1) + F(i) > 0)
if(dp[x] > max)
max = dp[x];
}
else
{
dp[x] = 0;
if(dp[x] > max)
max = dp[x];
}
}
}
}
cout << max <<endl;
}
return 0;
}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: