To The Max(最大子矩阵问题)

深藏阁楼爱情的钟 2022-08-05 05:05 266阅读 0赞

To The Max

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

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

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

Sample Output

  1. 15

这个是动态规划的最大子矩阵,跟最大子段的区别就是它是二维

的!所以要把它压缩成一维!这里的意思就是先算出每一列,再

算出每一行

这一题就是将一维的最大字段和扩展到二维,在一维的求最大字段和的过程中是这样操作的:

  1. int max_sum(int n)
  2. {
  3. int i, j, sum = 0, max = -10000;
  4. for(i = 1; i <= n; i++)
  5. {
  6. if(sum < 0)
  7. sum = 0;
  8. sum += a[i];
  9. if(sum > max)
  10. max = sum;
  11. }
  12. return sum;
  13. }

扩展到二维的时候也是同样的方法,不过需要将二维压缩成一维,所以我们要将数据做一下处理,使得map[i][j]从表示第i行第j个元素变成表示第i行前j个元素和,这样map[k][j]-map[k][i]就可以表示第k行从i->j列的元素和。只要比一维多两层循环枚举i和j就行了。

  1. #include<cstdio>
  2. #include<iostream>
  3. #include<cstring>
  4. using namespace std;
  5. int map[105][105];
  6. int maxs;
  7. int main()
  8. {
  9. int n,i,j,v,k,sum;
  10. while(cin>>n)
  11. {
  12. memset(map,0,sizeof(map));
  13. for(i=1;i<=n;i++)
  14. {
  15. for(j=1;j<=n;j++)
  16. {
  17. cin>>v;
  18. map[i][j]=map[i][j-1]+v;
  19. }
  20. }//这个的每一列的每一个数字是前面的数字之和!这样就确保了每一列是线性的!
  21. maxs=-100000;
  22. for(i=1;i<=n;i++)
  23. {
  24. for(j=i;j<=n;j++)
  25. {
  26. sum=0;
  27. for(k=1;k<=n;k++)
  28. {
  29. sum+=map[k][j]-map[k][i-1];//每一行再进行线性就可以实现二维数组的动态规划!
  30. if(sum<0)
  31. {
  32. sum=0;
  33. }
  34. if(sum>maxs)
  35. {
  36. maxs=sum;
  37. }
  38. }
  39. }
  40. }
  41. cout<<maxs<<endl;
  42. }
  43. }

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java矩阵

    问题描述 小明有一个大小为 � × � N×M 的矩阵, 可以理解为一个 � N 行 � M 列的二维数组。 我们定义一个矩阵 �

    相关 矩阵求和问题

    给定一个N\N的矩阵,计算最大子矩阵和。 思路: 最大子段和问题可以用动态规划在O(n)内解决,该题可以借助最大子段和的解法来做。我们考虑第i行到第j行的子矩阵,可以将i