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.
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:
- #include <stdio.h>
- #define MAX 101
- int main()
- {
- int n;
- int a[MAX][MAX]={0};
- int colsum[MAX][MAX]={0};
- int max=0,sum;
- scanf("%d",&n);
- for(int i=0;i<n;i++)
- for(int j=1;j<=n;j++)
- {
- scanf("%d",&a[i][j-1]);
- colsum[i][j]=colsum[i][j-1]+a[i][j-1];
- }
- for(int i=0;i<n;i++)
- for(int j=i;j<=n;j++)//从第i行到第j行
- {
- sum=0;
- for(int k=0;k<n;k++)//每列的和
- {
- sum+=colsum[k][j]-colsum[k][i];
- if(sum<0) sum=0;
- else if(sum>max) max=sum;
- }
- }
- printf("%d/n",max);
- return 0;
- }