POJ 1050 - To the Max

题目链接:http://poj.org/problem?id=1050

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. 

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?我也不知道求矩阵前缀和算不算DP……

我们用dp[i][j]表示这个矩阵前i行,前j列所有元素的和。

那么,我们求任何一个子矩阵 [x1,y1][x2,y2] ,就用dp[x2][y2]-dp[x2][y1]-dp[x1][y2]+dp[x1 - 1][y1 - 1]表示即可;

然后,直接四重循环枚举x1,x2,y1,y2就可得到答案。

 1 #include<cstdio>
 2 #include<cstring> 
 3 #define MAXN 105
 4 #define INF 0x3f3f3f3f
 5 int n,dp[MAXN][MAXN];
 6 int main()
 7 {
 8     while(scanf("%d",&n)!=EOF)
 9     {
10         memset(dp,0,sizeof(dp));
11         for(int i=1;i<=n;i++)
12         {
13             for(int j=1;j<=n;j++)
14             {
15                 int tmp;
16                 scanf("%d",&tmp);
17                 dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+tmp;
18             }
19         }
20         int ans=-INF;
21         for(int i=1;i<=n;i++)
22         {
23             for(int j=1;j<=n;j++)
24             {
25                 for(int ii=i;ii<=n;ii++)
26                 {
27                     for(int jj=j;jj<=n;jj++)
28                     {
29                         int now=dp[ii][jj]-dp[ii][j-1]-dp[i-1][jj]+dp[i-1][j-1];
30                         if(ans<now) ans=now;
31                     }
32                 }
33             }
34         }
35         printf("%d\n",ans);
36     }
37 }

 

posted @ 2017-07-26 20:59  Dilthey  阅读(456)  评论(0)    收藏  举报