poj1050TotheMax

来源:互联网 发布:激战2人族女捏脸数据 编辑:程序博客网 时间:2024/05/22 08:04
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. 

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 the sum of the maximal sub-rectangle.

4
0 -2 -7 0
9 2 -6 2 
-4 1 -4 1 
-1 8 0 -2
output

15
这个题目应该连着我上一次的那个“最大子字段和”的文章

地址是http://blog.csdn.net/dumpling5232/article/details/7757777

矩阵是二维的,压缩成一维的,然后求最大子字段和就可以了。

设sum[i][j] 表示第j列的,从第 1行累加到 第i行的结果。

循环分三层

第一层 i:1-n表示从第i行开始加

第二层j:i-n表示累加到第j行

第三层 k:1-n 表示从第k列开始求最大子字段和


代码

#include<iostream>#include<cstdio>#include<cmath>#include<cstdlib>#include<algorithm>#include<cstring>#include<string>using namespace std;int ans[110];int map[110][110];int sum[110][110];int dp[110];int maxm;int main(){    int n,i,j,k;    while(scanf("%d",&n)!=EOF)    {  for(i=1;i<=n;i++)        for(j=1;j<=n;j++)          scanf("%d",&map[i][j]);          maxm=map[1][1];       for(i=1;i<=n;i++) sum[1][i]=map[1][i];       for(i=2;i<=n;i++)       for(j=1;j<=n;j++)         sum[i][j]+=sum[i-1][j]+map[i][j];         for(i=1;i<=n;i++)         {             for(j=i;j<=n;j++)             {                 dp[1]=sum[j][1]-sum[i-1][1];                 for(k=2;k<=n;k++)                 {                     int temp=sum[j][k]-sum[i-1][k];                     dp[k]=max(dp[k-1]+temp,temp);                     if(maxm<dp[k]) maxm=dp[k];                 }             }         }         printf("%d\n",maxm);    }  return 0;}


原创粉丝点击