【POJ-1050】To 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-1050】To The Max(動態規劃)