POJ编程1----To the Max
题目要求
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.
即找到给定方阵的最大子矩阵的值。
矩阵降维加一维的动态规划
暴力检索会出现很多重叠子问题,浪费时间。所以考虑动态规划,参考了博客https://blog.csdn.net/hitwhylz/article/details/11848439的思路,先将矩阵降维,通过两重循环遍历,将不同的行对应元素相加,生成一个一维数组,对其使用动态规划。
设一维数组arr[],遍历,设以当前元素为结尾的一段的和最大为max1[],则max1[k]=max{max1[k-1]+arr[k],arr[k]},以此得到每一段的最大值,并每一步都和全局变量max比较,得到最大子矩阵的和。
示例代码
#include<iostream>
using namespace std;
int main()
{
int N;
int max = 0;
int data[100][100];
cin >> N;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cin >> data[i][j];
for (int i = 0; i < N; i++)
{
int arr[100] = { 0 };
for (int j = i; j < N; j++)
{
for (int k = 0; k < N; k++)
arr[k] += data[j][k];
int max1 = arr[0];
for (int k = 1; k < N; k++)
{
if (max1 > 0)
max1 = max1 + arr[k];
else
max1 = arr[k];
if (max1 > max)
max = max1;
}
}
}
cout << max << endl;
return 0;
}