POJ-1050-To the Max 解题报告
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
Source
【算法分析】
本题的输入需要小心。动态规划。
本题其实是最大子序列的扩展,由一维的扩展成二维的。
因此我们很自然的想到一维的做法。
一维例如:a1,a2,a3……an,则令f[i]为前i项的最大和。
有状态转移方程:f[0]=a[0];
if(f[i-1] < 0) f[i]=a[i];
Else f[i]=f[i-1]+a[i];
然后我们的任务就是把二维的转化为一维的就可以了。
即推出所有可能的列组合,如4列的矩阵,则其所有可能的列组合为:
1~4列,1+2列,2+3列,3+4列,1+2+3列,2+3+4列,1+2+3+4列。10种情况。
实现方法是,a[i][j]+=a[i][j-1] , a[i][j]为第i行的前j列的和。
则第k 列到第j列的和为,a[i][j]-a[i][k-1]
这样就转化成一维了,再用一维的方法算出即可。
【代码】
#include <stdio.h>
#include <string.h>
#define max 110
long long a[max][max],b[max*max][max*max],f[max];
int n;
int dp(int j)
{
long long p;
int i;
f[0]=b[0][j];
for( i=1;i<n;i++) {
if(f[i-1] >0 ) f[i]=f[i-1]+b[i][j];
else f[i]=b[i][j];
}
p=f[0];
for(i=1;i<n;i++)
if(f[i] > p) p=f[i];
return p;
}
int main()
{
int i,j,k,m,flag;
long long h,p;
char ch;
scanf("%d",&n);
getchar();
flag=0;
for(i=0;i<n;i++) { //初始化 ,注意空格,负号等问题
for(j=0;j<n;) {
scanf("%c",&ch);
if(ch!=10 && ch!= 32) {
if(ch=='-') flag=2;
else {
if(flag==1) {
j--;
if(a[i][j]<0) a[i][j]=a[i][j] * 10 - (ch-'0');
else a[i][j]=a[i][j] * 10 + (ch-'0');
}
if(flag==2) a[i][j]=-(ch-'0');
if(flag==0) a[i][j]=ch-'0';
flag=1;
j++;
}
}
else flag=0;
}
}
getchar();
for(j=0;j<n;j++)
for(i=0;i<n;i++)
b[i][j]=a[i][j];
for(j=1;j<n;j++) //记录每行中前j列的数字之和a[i][j]
for(i=0;i<n;i++) //那么对于每一行j列于k列之间数字和= a[i][k] - a[i][j-1];
a[i][j]+=a[i][j-1];
m=n;
for(j=0,k=1;k<n-1;j++) { //类似于反杨辉三角的存储
if(j >= n-k) { j=0;k++;}
for(i=0;i<n;i++) {
if(j-1<0 ) b[i][m]=a[i][j+k];
else b[i][m]=a[i][j+k]-a[i][j-1];
}
m++;
}
p=dp(0);
for(j=1;j<m;j++) {
h=dp(j);
if(h>p) p=h;
}
printf("%lld/n",p);
return 0;
}