To the Max(矩阵压缩)
To the Max
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 20000/10000K (Java/Other)
Total Submission(s) : 2 Accepted Submission(s) : 2
Problem Description
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.
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 * 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
题解:dp问题善于把复杂问题简单化,过程异途同归;
代码:
1 #include<stdio.h> 2 #include<string.h> 3 #define MAX(x,y)(x>y?x:y) 4 const int INF=-0x3f3f3f3f; 5 const int MAXN=110; 6 int ans,N; 7 void maxline(int *a){ 8 int sum=0; 9 for(int i=1;i<=N;i++){ 10 // printf("%d ",a[i]); 11 if(sum>0)sum+=a[i];//保证sum+a[i]>a[i]; 12 else sum=a[i]; 13 // printf("%d\n",sum); 14 ans=MAX(ans,sum); 15 } 16 } 17 int main(){ 18 int s[MAXN],dp[MAXN],map[MAXN][MAXN]; 19 while(~scanf("%d",&N)){ 20 int temp; 21 ans=INF; 22 for(int i=1;i<=N;i++) 23 for(int j=1;j<=N;j++) 24 scanf("%d",&map[i][j]); 25 for(int i=1;i<=N;i++){ 26 for(int j=i;j<=N;j++){ 27 if(j-i)for(int k=1;k<=N;k++) 28 map[i][k]+=map[j][k]; 29 maxline(map[i]);//这里是i代表每列从i行到j行的元素和 30 } 31 } 32 printf("%d\n",ans); 33 } 34 return 0; 35 }