POJ 1050 To the Max (動規)

To the Max
Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 40302
Accepted: 21329

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

Greater New York 2001

在一維情況下最大連續子段和的求法是從左到有順序掃描數據,以0爲邊界,當累加和小於0時則重置爲0.動態規劃的狀態轉移方程爲

s=max{si-1+ai,ai},該方程和前面的描述是等價的。本題是對一維最大子段和的擴展,思路是從上到下找出所有的連續行(如第i行到第j行),然後計算每列從第i行到第j行的和,之後對這n個列的和進行一維最大子段和的計算,並找出最大的值。

最大子矩陣,首先一行數列很簡單求最大的子和,我們要把矩陣轉化成一行數列,就是從上向下在輸入的時候取和,map[i][j]表示在J列從上向下的數和,這樣就把一列轉化成了一個點,再用雙重,循環,任意i行j列開始的一排數的最大和,就是最終的最大和

 假設最大子矩陣的結果爲從第r行到k行、從第i列到j列的子矩陣,如下所示(ari表示a[r][i],假設數組下標從1開始):
  | a11 …… a1i ……a1j ……a1n |
  | a21 …… a2i ……a2j ……a2n |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ar1 …… ari ……arj ……arn |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ak1 …… aki ……akj ……akn |
  |  .     .     .    .    .     .    .   |
  | an1 …… ani ……anj ……ann |

 那麼我們將從第r行到第k行的每一行中相同列的加起來,可以得到一個一維數組如下:
 (ar1+……+ak1, ar2+……+ak2, ……,arn+……+akn)
 由此我們可以看出最後所求的就是此一維數組的最大子斷和問題,到此我們已經將問題轉化爲上面的已經解決了的問題了。

代碼:
#include <iostream>
using namespace std;
#define M 110
int main()
{
	int a[M][M]={0},c[M][M]={0}; //a[M][M]用來存數,c[M][M]就是存這行到這一列的和。
	int i,j,n,max=0,sum,k;
    scanf("%d",&n);
	for(i=0;i<n;i++)
	  for(j=1;j<=n;j++)
	  {
        scanf("%d",&a[i][j-1]);
        c[i][j]=c[i][j-1]+a[i][j-1];   //一行的下一個數和上面所有數的和。
	  } 
	  for(i=0;i<n;i++)
		  for(j=i;j<=n;j++)
		  {
			  sum=0;
			  for(k=0;k<n;k++)
			  {
				  sum+=c[k][j]-c[k][i];
				  if(sum<0) sum=0;  //小於0就相當於不用取了,直接去掉 
				  else if(sum>max) max=sum;
			  }
		  }
		  printf("%d\n",max);
		  return 0;
}

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