poj1050 2010.3.5
Poj 1050 To the Max
【关键字】
动态规划
【摘要】
读入一个n*n的数组,从里面任意截取一个矩阵,使得矩阵所包含的数字的和最大.
【正文】
1、题目描述
To the Max
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 17636 Accepted: 8984
Description
Given a two-dimensional array of positiveand negative integers, a sub-rectangle is any contiguous sub-array of size 1*1or greater located within the whole array. The sum of a rectangle is the sum ofall the elements in that rectangle. In this problem the sub-rectangle with thelargest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle ofthe 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 ofintegers. The input begins with a single positive integer N on a line byitself, indicating the size of the square two-dimensional array. This isfollowed by N^2 integers separated by whitespace (spaces and newlines). Theseare the N^2 integers of the array, presented in row-major order. That is, allnumbers 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 bein the range [-127,127].
Output
Output the sum of the maximalsub-rectangle.
Sample Input
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0-2
Sample Output
15
Source
Greater New York 2001
2、算法分析
这个题目很经典的说,O(N^3)的DP。
首先偶们考察这样的题目,简化版:
已知一列数,求任意连续若干个数和的最大值。
SAMPLE: 3 2 -6 2 -1 7
原数3 2 -6 2 -1 7
处理3 5 -1 2 1 8
因为是连续若干个自然数的和,那么,前面的某个数字取与不取的条件在于:以前面这
个数字为结尾的连续数的和最大值是否大于0,如果大于0,那么这个数字必然要会出现
在包括数字的序列中,否则无法做到最大。
所以,显然。处理的原则是maxn[i]=max{0,maxn[i-1]}+a[i];由于无须记录位置。所以,可以直接用一个变量sum代替maxn数组。O(n)的扫描即可。
单列数字的问题解决了,下面我们考察多列数字的
sample:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
我们可以将多列数字转换成单列数字来做!可以这样设想,结果是一个长方形,我们把
他压扁,使得宽为1。
引入辅助数组st,st[i][j]代表第i列从第1行开始的数字累加到第j行的值。那么,我们
每次压扁的时候,就可以用st[i][j]-st[i][k-1]来表示第i列从第k个数字累加到第j个
数字的值。达到压缩的效果。然后用上面单列数字的方法来做。算法时间复杂度O(N^3)
3、源码
#include <stdio.h>
#include <string.h>
#define mt 101
void main()
{
int a[mt][mt];
int st[mt][mt];
int p,k,n,i,j,sum,maxn;
scanf("%d",&n);
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
memset(st,0,sizeof(st));
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
st[i][j]=st[i][j-1]+a[j][i];
maxn=0;
for (i=1;i<=n;i++)
{
for (j=i;j<=n;j++)
{
sum=st[1][j]-st[1][i-1];
for (k=2;k<=n;k++)
{
if (sum>0)
sum+=st[k][j]-st[k][i-1];
else
sum=st[k][j]-st[k][i-1];
if (sum>maxn) maxn=sum;
}
}
}
printf("%d\n",maxn);
}