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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值