HDU 1081 To The Max-动态规划-[解题报告] C++

问题描述 :

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.

输入:

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 the sum of the maximal sub-rectangle.

样例输入:

4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2

样例输出:

15

HDU-1081 http://acm.hdu.edu.cn/showproblem.php?pid=1081

  一道简单的求子矩阵的最大和问题,由于数据给的比较下,n只有100,可以使用常规的O(N^3)的时间复杂度的算法解,枚举每一行以及改行下面的所有的行的和,时间复杂度为O(N^2),然后对压缩后的每一行进行dp,时间复杂度为线性的O(N),最后总的时间复杂度为O(N^3)

  dp的状态转移方程:dp[i] = MAX(dp[i-1] + tmp[i], dp[i])

view source
01 #include <stdio.h>
02  #include <string.h>
03  #define MAX(x, y) ((x) > (y) ? (x) : (y))
04  int main(void)
05  {
06      int map[101][101];
07      int dp[101], tmp[101];
08      int max;
09      int i, j, t;
10      int n;
11   
12      while(scanf("%d", &n) != EOF)
13      {
14      for(i = 0; i < n; i++)
15          for(j = 0; j < n; j++)
16          scanf("%d", &map[i][j]);
17      max = -10000000;
18      for(i = 0; i < n; i++)
19      {
20          memset(tmp, 0, sizeof(tmp));
21          for(t = i; t < n; t++)
22          {
23          for(j = 0; j < n; j++)
24              tmp[j] += map[t][j];
25   
26          dp[0] = tmp[0];
27          for(j = 1; j < n; j++)
28          {
29              /*dp[j] = MAX(dp[j-1] + tmp[j], tmp[j]);
30              max = MAX(dp[j], max);*/
31              if(dp[j-1] > 0)
32              dp[j] = dp[j-1] + tmp[j];
33              else
34              dp[j] = tmp[j];
35              if(dp[j] > max)
36              max = dp[j];
37          }
38          }
39      }
40      printf("%d\n", max);
41      }
42      return 0;
43  }

 

你可能感兴趣的:(HDU 1081 To The Max-动态规划-[解题报告] C++)