hdu1081 To The Max (最大子矩阵和)

To The Max

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4592    Accepted Submission(s): 2165


Problem Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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.
 

 

Input
The input consists of an N x 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
 
分析:通过转换成最大字段和
第一步:s[i][k]=a[1][k]+ …… +a[i][k]
第二步:t[k]=s[j][k]-s[i][k];
第三步:求t[]的最大字段和
 
原因:假设最终的子矩阵和行是i、j;
那么最终是求(a[i][1]+ …… +a[j][1],a[i][2]+ …… +a[j][2], …… ,a[i][n]+ …… +a[j][n])的最大字段和。
 
View Code
 1 #include<iostream>
 2 #include<cstdio>
 3 #define N 110
 4 
 5 using namespace std;
 6 
 7 int a[N][N],s[N][N];
 8 
 9 int max(int A,int B)
10 {
11     return A>B?A:B;
12 }
13 
14 int maxsum(int *A,int n)
15 {
16     int i,t,ans;
17     ans=A[1];t=0;
18     for(i=1;i<=n;i++)
19     {
20         t=max(A[i],t+A[i]);
21         if(ans<t)
22             ans=t;
23     }
24     return ans;
25 }
26 
27 int main()
28 {
29     int n,i,j,k,ans,ret,t[N];
30     while(scanf("%d",&n)==1)
31     {
32         for(i=0;i<=n;i++)
33             s[i][0]=s[0][i]=a[i][0]=a[0][i]=0;
34         for(i=1;i<=n;i++)
35             for(j=1;j<=n;j++)
36             {
37                 scanf("%d",&a[i][j]);
38                 s[i][j]=s[i-1][j]+a[i][j];
39             }
40         ans=-100000000;
41         for(i=0;i<=n;i++)
42         {
43             for(j=i+1;j<=n;j++)
44             {
45                 for(k=1;k<=n;k++)
46                 {
47                     t[k]=s[j][k]-s[i][k];
48                 }
49                 ret=maxsum(t,n);
50                 if(ans<ret)
51                     ans=ret;
52             }
53         }
54         printf("%d\n",ans);
55     }
56     return 0;
57 }

 

posted @ 2012-07-08 16:49  mtry  阅读(2066)  评论(0编辑  收藏  举报