HDU 1081 (DP)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1081

 

To The Max

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


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
 
 
题意分析:二维矩阵压缩成一维矩阵,三个for循环实现:
             for (int i=0; i<n; i++)
                   for (int j=i; j<n; j++)  //注意这里的j=i;
                         for (int k=0; k<n; k++)
 
              原理:首先把每一列的最大值求出来,二维就变成的一维,就变成了求最大数列和的问题了,但要注意每次更新。
 
 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 int a[111][111],dp[111],n;
 6 int sum,ans;
 7 
 8 int main ()
 9 {
10     int i,j,k;
11     while (scanf ("%d",&n)==1)
12     {
13         for (i=0; i<n; i++)
14             for (j=0; j<n; j++)
15                 scanf ("%d",&a[i][j]);
16         ans = -99999999;
17         for (i=0; i<n; i++)
18         {
19             memset(dp, 0, sizeof(dp));//每次更新dp清零
20             for (j=i; j<n; j++)
21             {
22                 sum = -1;//同上
23                 for (k=0; k<n; k++)//每列元素相加
24                 {
25                     dp[k] += a[j][k];
26                 }
27                 for (k=0; k<n; k++)//找到和最大的那列
28                 {
29                     if (sum > 0)
30                         sum += dp[k];
31                     else
32                         sum = dp[k];
33                     if (sum > ans)
34                         ans = sum;
35                 }
36             }
37         }
38         printf ("%d\n",ans);
39     }
40     return 0;
41 }
View Code

 

posted @ 2015-03-23 20:35  敲敲代码,打打酱油  阅读(98)  评论(0编辑  收藏  举报