POJ-1050To The Max(动态规划)
Posted bdflyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ-1050To The Max(动态规划)相关的知识,希望对你有一定的参考价值。
To the Max
Time Limit: 1000MS
Memory Limit: 10000K
Description
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.
Input
The input consists of an N * 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
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2
Sample Output
15
题目大意
给定一个N*N的二位数组Matrix,求该二维数组的最大子矩阵和。
题目分析
- 暴力枚举
用4个循环,枚举出所有的子矩阵,再给每个子矩阵求和,找出最大的,肯定会超时,不可用。
时间复杂度:O(N^6)
- 动态规划 (标准解法)
把二维转化为一维再求解。
有子矩阵:矩阵中第i行至第j行的矩阵。
用数组ColumnSum[k]记录子矩阵中第k列的和。
最后对ColumnSum算出最大子段和进行求解。
时间复杂度:O(N^3)
关于最大子段和:
有一序列a=a1 a2 ... an
,求出该序列中最大的连续子序列。
比如序列1 -2 3 4 -5
的最大子序列为3 4
,和为3+4=7。
动态转移方程:DP[i]=max(DP[i-1]+a[i], a[i])
时间复杂度:O(N)
(最大子段和的具体过程网上有,我就不多说了)
代码
#include <cstdlib>
#include <cstdio>
using namespace std;
#define INF 0x7f7f7f7f
#define max(a, b) (((a)>(b))?(a):(b))
int N;
int Matrix[110][110];
int Answer = -INF;
int main()
{
scanf("%d", &N);
for(int i = 1; i <= N; ++ i)
for(int j = 1; j <= N; ++ j)
scanf("%d", &Matrix[i][j]);
for(int i = 1; i <= N; ++ i)
{
int ColumnSum[110] = {0};
for(int j = i; j <= N; ++ j)
{
int DP[110] = {0};
for(int k = 1; k <= N; ++ k)
{
ColumnSum[k] += Matrix[j][k];
// 求最大子段和
DP[k] = max(DP[k-1] + ColumnSum[k], ColumnSum[k]);
Answer = max(DP[k], Answer);
}
}
}
printf("%d\n", Answer);
return 0;
}
以上是关于POJ-1050To The Max(动态规划)的主要内容,如果未能解决你的问题,请参考以下文章