POJ 1050 To the Max
枚举行之间的组合,在求最大连续和。
上学期好像就做过的。。。。。和City Game有种一样的感觉。
To the Max
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 35605 | Accepted: 18697 |
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.
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 * 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
40 -2 -7 0 9 2 -6 2-4 1 -4 1 -18 0 -2
Sample Output
15
Source
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 int a[110][110]; 7 int b[110]; 8 9 int main() 10 { 11 int n; 12 cin>>n; 13 for(int i=0;i<n;i++) 14 for(int j=0;j<n;j++) 15 cin>>a[i][j]; 16 17 int maxn=-999999999; 18 19 for(int i=0;i<n;i++) 20 { 21 for(int j=0;j<=i;j++)///[i,j]之间的和 22 { 23 memset(b,0,sizeof(b)); 24 for(int l=0;l<n;l++) 25 for(int k=j;k<=i;k++) 26 { 27 b[l]+=a[k][l]; 28 } 29 int sum=0; 30 for(int m=0;m<n;m++) 31 { 32 sum+=b[m]; 33 maxn=max(maxn,sum); 34 if(sum<0) sum=0; 35 } 36 } 37 } 38 39 cout<<maxn<<endl; 40 41 return 0; 42 }