杭电1081——to the max(动态规划和暴力法解)
To The Max
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
题目我起先用暴力法来解答,不过,通不过,超时,后来参考了一下别人的思想吧!没想到这道题还可以用动归的方法解答,很吃惊啊!
代码如下:
[cpp]
//这个程序可以求出m*n的矩阵某一块的最大值
//这种搜索算法没有错误!但是超时,因此还要进一步优化算法!
//这道题的题意说的比较模糊,题目里没有说要多个测试数据,弄得我只处理了一次,导致老是错误,又找不到问题所在!
/*
#include<iostream>
#include<cstdio>
using namespace std;
const int MAX=10010;
int arr[MAX];
int main()
{
int s,max=-200;
int we=0;
int m,n;
while(scanf("%d",&arr[0])!=EOF)
{
//cin>>arr[0];//输入方阵的维数
m=n=arr[0];
for(int i=1;i<=arr[0]*arr[0];i++)
cin>>arr[i];
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)//这里是表示块数的大小,i*j
for(int p=1;m-p>=i-1 ;p++)
for(int q=1;n-q>=j-1 ;q++)//搜索路线,自上而下,自左向右
{
int cur=p+m*(q-1);
int count=0;
int temp=cur;
int temp1=1;
s=0;
//cout<<"第"<<we<<"次搜索: "<<endl;
//cout<<"起点是 行数"<<p<<","<<"列数"<<q<<endl;
//cout<<"p="<<p<<",n="<<n<<endl;
for(int k=1;k<=i*j;k++)
{
//cout<<arr[temp]<<" ";
s=s+arr[temp];
count++;
temp++;
if(count>=i)
{
temp=cur+temp1*m;
temp1++;
count=0;
}
}
//cout<<endl;
//we++;
if(s>max)
max=s;
}
cout<<max<<endl;
//system("pause");
}
return 0;
}
*/
#include<iostream>
#include<cstdio>
using namespace std;
int arr[101][101];
int sum[101],dp[101];
int main()
{
int i,j,k,p,n;
while(scanf("%d",&n)!=EOF)
{
int max=-200;
memset(sum,0,sizeof(sum));
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
for(j=
补充:软件开发 , C++ ,