您的位置:首页 > 其它

HDU 1081 To The Max (DP)

2014-07-31 00:37 459 查看
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]结尾的最大连续子序列)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int num[101][101];
int ans;
int main()
{
int n,i,j,k,a;
while(scanf("%d",&n)!=EOF)
{
memset(num,0,sizeof(num));
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
scanf("%d",&a);
num[i][j]=num[i][j-1]+a;
}
}
int maxn=-0x3fffffff;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
ans=-1;
for(k=1;k<=n;k++)
{
if(ans>0)
ans+=num[k][i]-num[k][j-1];
else
ans=num[k][i]-num[k][j-1];
if(ans>maxn)
maxn=ans;
}
}
}
printf("%d\n",maxn);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: