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

原題鏈接 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);
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章