poj 1050 dp

来源:互联网 发布:coldplay好听的歌 知乎 编辑:程序博客网 时间:2024/05/21 11:28

 

如题:http://poj.org/problem?id=1050

 

To the Max
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 42128 Accepted: 22399

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

40 -2 -7 0 9 2 -6 2-4 1 -4  1 -18  0 -2

Sample Output

15

Source

Greater New York 2001

 

 

题目大意:给出一个N*N的矩阵,求它的子矩阵的最大和.

 

思路:先看一题:给出一个数列,求出它的某一段的最大和,这一题很简单,dp[i]表示前i的元素之前的最大和。

dp[i]=max(dp[i-1]+a[i],a[i]).

 

那么这一题就是上面那个题的变形,只不过变成2维的。

我们将二维压缩,每一行和是一个元素,然后再用上面数列的处理求出连续最大和就行了。

使用两个变量i,j。他们可以看成是2条直线,将原矩阵横向分割。每次处理i到j行的那个子矩阵,累加和到新数组,然后dp。

 

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define MAXN 105
#define INF 0x0fffffff
#define max(a,b)(a>b?a:b)

int a[MAXN][MAXN];
int col[MAXN];
int dp[MAXN];
int N;

int main()
{
// freopen("C:\\1.txt","r",stdin);
 cin>>N;
 int i,j,k,l;
 for(i=0;i<N;i++)
  for(j=0;j<N;j++)
   scanf("%d",&a[i][j]);
 int sum=-INF;
 for(i=0;i<N;i++)    
  for(j=i;j<N;j++)
  {
   for(k=0;k<N;k++)
     col[k]=0;
   for(k=0;k<N;k++)
    for(l=i;l<=j;l++)
     col[k]+=a[l][k];
            for(k=0;k<N;k++)
    dp[i]=0;
   for(k=0;k<N;k++)
   {
    if(k==0)
     dp[k]=col[k];
    else
     dp[k]=max(dp[k-1]+col[k],col[k]);
    if(dp[k]>sum)
     sum=dp[k];
   }
  }
 cout<<sum<<endl;
 return 0;
}

 

0 0
原创粉丝点击