hdu-------1081To The Max

时间:2023-12-27 22:27:13

To The Max

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7681    Accepted Submission(s): 3724

Problem 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
Source
这道题个人觉得是到灰常好的题目,适合不同层次的人做,求的是最大连续子矩阵和....
方法一:
简单的模拟即可。首先求出每个阶段只和,然后得到这个状态,然后进行矩阵规划,求最大值即可
代码浅显易懂:
hdu-------1081To The Max
 #include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
int arr[][];
int sum[][];
int main()
{
int nn,i,j,ans,temp;
// freopen("test.in","r",stdin);
while(scanf("%d",&nn)!=EOF)
{
ans=;
memset(sum,,sizeof(sum));
for(i=;i<=nn;i++)
{
for(j=;j<=nn;j++)
{
scanf("%d",&arr[i][j]);
sum[i][j]+=arr[i][j]+sum[i][j-]; //求出每一层逐步之和
}
}
for(i=;i<=nn;i++)
{
for(j=;j<=nn;j++)
{
sum[i][j]+=sum[i-][j]; //在和的基础上,逐步求出最大和
}
}
ans=;
for(int rr=;rr<=nn;rr++)
{
for(int cc=;cc<=nn;cc++)
{
for(i=rr;i<=nn;i++)
{
for(j=cc;j<=nn;j++)
{
temp=sum[i][j]-sum[i][cc-]-sum[rr-][j]+sum[rr-][cc-];
if(ans<temp) ans=temp;
}
}
}
}
printf("%d\n",ans);
}
return ;
}

方法二:

采用状态压缩的方式进行DP求解最大值......!

代码:

     /*基于一串连续数字进行求解的扩展*/
/*coder Gxjun 1081*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
const int nn=;
int arr[nn][nn],sum[nn][nn];
int main()
{
int n,i,j,maxc,res,ans;
// freopen("test.in","r",stdin);
while(scanf("%d",&n)!=EOF)
{
memset(sum,,sizeof(sum));
for(i=;i<=n;i++)
for(j=;j<=n;j++)
{
scanf("%d",&arr[i][j]);
sum[j][i]=sum[j][i-]+arr[i][j];
}
ans=;
for(i=;i<=n;i++){ for(j=i;j<=n;j++)
{
res=maxc=;
for(int k=;k<=n;k++)
{
maxc+=sum[k][j]-sum[k][i-];
if(maxc<=) maxc=;
else
if(maxc>res) res=maxc;
}
if(ans<res) ans=res;
}
}
printf("%d\n",ans);
}
return ;
}