您的位置:首页 > 其它

PKU-1050 To the Max (最大子矩阵和)

2013-05-05 21:40 337 查看
原题链接 http://poj.org/problem?id=1050
To the Max

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


Source Code

/*
最大子段和:
设max[j]为matrix[0....j]中的最大子段之和,max[j]当前只有两种情况:
1)最大子段一直连续到matrix[j]; (2)以matrix[j]为起点的子段。
注意!
如果当前最大子段没有包含matrix[j],如果没有包含的话,在算max[j]之前我们就已经算出来了。
得到max[j]的状态转移方程为:max[j] = max { max[j-1] + matrix[j], matrix[j]}
所求的最大子段和为max{ max[j], 0<=j<n}

最优子矩阵和连续最大和的异同:

1、  所求的和都具有连续性;

2、  连续最大和是一维问题,最优子矩阵是二维问题

另外,对于一个矩阵而言,如果我们将连续j行的元素纵向相加,并对相加后所得的数列求连续最大和,
则此连续最大和就是一个行数为j的最优子矩阵!由此,我们可以将二维的矩阵压缩成一维矩阵,转换为线性问题

*/

#include <iostream>
using namespace std;

//记录最大子段和的起点,终点,值
int start, end, MaxValue;

void MaxSum(int *array, int len) {
int i, newStart = 0;
int sum = 0;
for (i = 0; i < len; i++) {
if (sum < 0) {
sum = array[i];
newStart = i;
} else {
sum += array[i];
}

if (sum > MaxValue) {
MaxValue = sum;
start = newStart;
end = i;
}
}

}

int main() {
int len, i, j, k;
int num[101][101], sums[101];
while (scanf("%d", &len) != EOF) {
for (i = 0; i < len; i++) {
for (j = 0; j < len; j++) {
scanf("%d", &num[i][j]);
}
}

MaxValue = num[0][0];

/*
i = 0; j = 0, 1, 2, 3……sums[]存的依次是第1行,1~2行,1~3行,1~4行每一列的和……
i = 1; j = 1, 2, 3, 4……sums[]存的依次是第2行, 2~3行, 2~4行,2~5行每一列的和……
i = 2; j = 2, 3, 4, 5……sums[]存的依次是第3行, 3~4行, 3~5行,3~6行每一列的和……
………………
(每次更新sums的值都是在之前的计算结果上每一列分别加上当前行的值)
*/
for (i = 0; i < len; i++) {
memset(sums, 0, sizeof(sums));
for (j = i; j < len; j++) {
for (k = 0; k < len; k++) {
sums[k] += num[j][k];
}
MaxSum(sums, len);
}
}
printf("%d\n", MaxValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: