POJ 1050 to max

to max
Time Limit: 1000 MS   Memory Limit: 10000K
Total submissions: 51175   Accepted: 27064

describe

Given a two-dimensional array of positive and negative integers, subrectangles are adjacent subarrays of any size 1*1 or larger, located throughout the array. The sum of a rectangle is the sum of all elements in that rectangle. In this problem, the subrectangle with the largest sum is called the largest subrectangle.
As an example, the largest subrectangle 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 there are 15 sheets.

enter

The input consists of n*n arrays. The input first starts with a positive integer n on a line indicating the size of the squared two-dimensional array. Next are n^2 integers, separated by spaces (space and space). These are 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 high as 100. The numbers in the array will be in the range [-127127].

output

Output the sum of the largest subrectangles.

sample input

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

8  0 -2

Sample output

15

source


Examination: Dynamic Programming Maximum Subsection Sum

Submission: One AC

Harvest: Recognize the next largest continuous subsection and

In the one-dimensional case, the calculation method of the maximum continuous sub-segment sum is to scan the data sequentially from the left, with 0 as the boundary, and reset to 0 when the accumulated sum is less than 0. The state transition equation of dynamic programming is:

s=max{si-1+ai,ai},该方程和前面的描述是等价的。本题是对一维最大子段和的扩展,思路是从上到下找出所有的连续行(如第i行到第j行),然后计算每列从第i行到第j行的和,之后对这n个列的和进行一维最大子段和的计算,并找出最大的值。

AC_CODE:

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #define MAX 101  
  3. int main()  
  4. {  
  5.     int n;  
  6.     int a[MAX][MAX]={0};  
  7.     int colsum[MAX][MAX]={0};  
  8.     int max=0,sum;  
  9.     scanf("%d",&n);  
  10.     for(int i=0;i<n;i++)  
  11.         for(int j=1;j<=n;j++)  
  12.         {  
  13.             scanf("%d",&a[i][j-1]);  
  14.             colsum[i][j]=colsum[i][j-1]+a[i][j-1];  
  15.         }  
  16.     for(int i=0;i<n;i++)  
  17.         for(int j=i;j<=n;j++)//从第i行到第j行  
  18.         {  
  19.             sum=0;  
  20.             for(int k=0;k<n;k++)//每列的和  
  21.             {  
  22.                 sum+=colsum[k][j]-colsum[k][i];  
  23.                 if(sum<0) sum=0;  
  24.                 else if(sum>max) max=sum;  
  25.             }  
  26.         }  
  27.     printf("%d/n",max);  
  28.     return 0;  
  29. }  
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325901395&siteId=291194637