To the Max 二維dp(一維的變形)
阿新 • • 發佈:2019-04-01
hole may b- separate 轉化 ima first lin con
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.
Output the sum of the maximal sub-rectangle.
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.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
Sample Input
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
Sample Output
15
題解:
看起來很難做的題目,但他讓我們想起 最大字段和,但那個是一維的。
那怎麽轉化二維為1維呢?
當然是枚舉了。
分別枚舉第 i 行到第 j 行 ,這裏的復雜度為O(n^2),然後在用字段和遍歷一遍,所以總的時間復雜度為O(n^3) 考慮到n不大,可行。
有一個問題是怎麽最快求第k列中,第 i 行道第 j 行的和,我們采用前綴和的方式。
由於網上多是行前綴和,這裏貼一個列前綴和的代碼
#include<stdio.h> #include<cmath> #include<iostream> #define INF 0x3f3f3f3f #define me(a,b) memset(a,b,sizeof(a)) #define N 102 typedef long long ll; using namespace std; int n,a[N][N],dp[N][N],t,sum,ans; int main() { //freopen("input.txt","r",stdin); cin>>n; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cin>>t; a[i][j]=a[i][j-1]+t;//記錄前綴和 } } for(int i=1;i<=n;i++) { for(int j=i;j<=n;j++) //枚舉,第i列道第j列 { sum=0; for(int k=1;k<=n;k++)//最大子序列遍歷一遍 { int t=a[k][j]-a[k][i-1];//t代表: 第k行中,第 i 列到第 j 列的和 sum+=t; sum=sum<0?0:sum; //<0則置為0 if(sum>ans) ans=sum; } } } cout<<ans; }
To the Max 二維dp(一維的變形)