首页 > ACM题库 > HDU-杭电 > HDU 1081 To The Max-动态规划-[解题报告] C++
2013
11-27

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

To The Max

问题描述 :

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])

#include <stdio.h>
 #include <string.h>
 #define MAX(x, y) ((x) > (y) ? (x) : (y))
 int main(void)
 {
     int map[101][101];
     int dp[101], tmp[101];
     int max;
     int i, j, t;
     int n;
 
     while(scanf("%d", &n) != EOF)
     {
     for(i = 0; i < n; i++)
         for(j = 0; j < n; j++)
         scanf("%d", &map[i][j]);
     max = -10000000;
     for(i = 0; i < n; i++)
     {
         memset(tmp, 0, sizeof(tmp));
         for(t = i; t < n; t++)
         {
         for(j = 0; j < n; j++)
             tmp[j] += map[t][j];
 
         dp[0] = tmp[0];
         for(j = 1; j < n; j++)
         {
             /*dp[j] = MAX(dp[j-1] + tmp[j], tmp[j]);
             max = MAX(dp[j], max);*/
             if(dp[j-1] > 0)
             dp[j] = dp[j-1] + tmp[j];
             else
             dp[j] = tmp[j];
             if(dp[j] > max)
             max = dp[j];
         }
         }
     }
     printf("%d\n", max);
     }
     return 0;
 }

 


  1. Thanks for using the time to examine this, I truly feel strongly about it and enjoy finding out far more on this subject matter. If achievable, as you achieve knowledge