acm pku 1050 To the Max的動態規劃方法

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

Greater New York 2001

 

       這是求二維數組的最大子數組問題,其更爲簡單的形式是求一維數組的最大連續子段問題。現在還是從一維數組的最大子段問題談起,對任意一個一維數組a[N](N個數),用b[j]表示a[N]中包括a[j]的前j個元素的最大連續子段的值。則必有:

b[j] = max{b[j-1]+a[j], a[j]}, 0j<N

這樣一維數組的最大子段值,就是max{b[j]} 0j<N。時間複雜度O(N)

       推廣到二維,就是要想辦法先將問題變爲類似於一維的問題。其具體思想是:對二維數組的包含N行的列進行連續列劃分,則共有N*N/2種,分別計算着N*N/2個矩陣的各列的和,則此時二維數組編成了一維數組,然後用一維數組求最大連續子段的方法可以求得需要的結果。時間複雜度O(N^3)

 

具體實現如下:

#include "iostream"

using namespace std;

 

const int N = 100;

int itg[N][N];

 

int MaxSum(int n, int itmp[])

{

       int i, max, tmp;

 

       max = itmp[0];

       tmp = itmp[0];

       for(i = 1; i < n; i++)

       {

       //     if(itmp > 0) tmp += itmp[i]; //靠,垃圾,害得我WA3次,下次一定好好選擇臨時變量了。

              if(tmp > 0) tmp += itmp[i];

              else tmp = itmp[i];

              if(max < tmp) max = tmp;

       }

       return max;

}

 

int main()

{

       int n;

       int i, j, k, max;

       int itmp[N], tmp;

 

       cin >> n;

       for(i = 0; i < n; i++)

       {

              for(j = 0; j < n; j++)

              {

                     cin >> itg[i][j];

              }

       }

 

       max = -200;

       for(i = 0; i < n; i ++)

       {

              memset(itmp, 0, sizeof(int)*N);

              for(j = i; j < n; j ++)

              {

                     for(k = 0; k < n; k ++) itmp[k] += itg[j][k];

                     tmp = MaxSum(n, itmp);

                     if(max < tmp) max = tmp;

              }

       }

       cout << max <<endl;

 

       return 0;

}

執行結果:

Problem: 1050

 

User: uestcshe

Memory: 252K

 

Time: 16MS

Language: C++

 

Result: Accepted

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