[ACM_动态规划] 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

 

题目大意:给一个n*n的整数矩阵,找出一个子矩阵使其和最大。

解题思路:• 该题其实就是最大连续和问题在二维空间上的推广。

• 先来看一下一维的最大连续和问题:

             ♣ 给出一个长度为n的序列A1,A2,A3.....An,求一个连续子序列Ai,Ai+1,....Aj使得元素总和最大。

           ♥ 我们以temp[i]表示以Ai结尾的子段中的最大子段和。在已知temp[i]的情况下,求temp [i+1]的方法是:

如果temp[i]>0 temp [i+1]= temp[i]+ai(继续在前一个子段上加上ai),否则temp[i+1]=ai(不加上前面的子段);

也就是说 状态转移方程:temp[i] = (temp[i-1]>0?temp[i-1]:0)+buf[i];

 int getMax(int buf[],int n){
int temp[],max=n*(-);
memset(temp,,sizeof(temp));
for(int i=;i<=n;i++){
temp[i] = (temp[i-]>?temp[i-]:)+buf[i];
if(max<temp[i])
max=temp[i];
}
return max;
}//求n元素序列buf[]的最大连续和函数

• 对于本题可以暴力枚举i到j行,针对每一个i到j行的一列元素求和就将i到j行的2维情况转化为1维情况:如:

0    -2  -7  0

9    2  -6  2

-4  1  -4   7

-1  8  0   -2

       取i=2,j=4,压缩为4(9 -4 -1),11(2 1 8),-10(-6 -4 0),7(2 7 -2)新的一维buf[]={4,11,-10,7},

然后求出buf[]的最大连续和就是2到4行范围内的最大矩阵的值。这样2层循环暴力所有i到j的情况取最大值即可!

 #include<iostream>
using namespace std;
int rect[][];//2维矩阵
int n,Max;;
int buf[];//中间1维矩阵
int getMax(){
int Temp[],max=n*(-);
memset(Temp,,sizeof(Temp));
for(int i=;i<=n;i++){
Temp[i]=(Temp[i-]> ? Temp[i-] : )+buf[i];
if(max<Temp[i])
max=Temp[i];
}
return max;
}//求最大连续和
void read(){
for(int i=;i<n;i++)
for(int j=;j<n;j++)
cin>>rect[i][j];
}//读入
int solve(){
Max=-*n;
for(int i=;i<n;i++){
for(int j=i;j<n;j++){//2层循环暴力所有i到j组合
memset(buf,,sizeof(buf));//压缩,2维变1维
for(int k=;k<n;k++)
for(int L=i;L<=j;L++)
buf[k]+=rect[k][L];
int d=getMax();//获得最大连续和
if(d>Max)Max=d;//更新Max值
}
}
return Max;
}//2维变1维暴力
int main(){
while(cin>>n){
read();
solve();
cout<<Max<<'\n';
}return ;
}
上一篇:poj 1050 To the Max(线性dp)


下一篇:POJ 1050 To the Max 二维最大子段和