題目描述
Now I think you have got an AC in Ignatius.L’s “Max Sum” problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S 1, S 2, S 3, S 4 … S x, … S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + … + S j (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + … + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x is not allowed).
But I`m lazy, I don’t want to write a special-judge module, so you don’t have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. _
輸入格式
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 … S n.
Process to the end of file.
輸出格式
Output the maximal summation described above in one line.
樣例輸入
1 3 1 2 3
2 6 -1 4 -2 3 -2 3
樣例輸出
6
8
題意:
給定長度爲N的序列S。定義sum(i , j) = s[i] + … + s[j]。給定m,求最大的m段連續序列和:
sum(i 1, j 1) + … + sum(i m, j m), 且沒有ix <= iy <=jx;
即在n個數中選出m組數, 每組數連續且不能相交, 求其所有組的最大和。
題解:
- 定義狀態:dp[i][j]爲以第j個數結尾的分爲i份的最大。
- 狀態轉移:一個以a[j]結尾的“i份最大劃分組”,要麼將是將a[j]加入a[j-1]結尾的“i份劃分組”,即dp[i][j-1]+a[j]; 要麼是a[j]單獨自成一組,與前面的“i-1份最大劃分組”結合,即max(dp[i-1][k])+a[j] 其中k < j
- 狀態方程:
- n2的空間複雜度對於1e6是明顯超限的。需要優化。
因爲我們只需要劃分成m份的最大和,中間的過程都不需要(和揹包問題類似),所以我們可以只用一維數組滾動就行了。 - 對於dp[i-1][k]:上一層劃分的之前的最大值,可以用額外的數組lastmax來存儲,在滾動時維護。
- 在m次循環後,dp[n]數組中的最大值即爲最後所求答案
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000005
#define inf 0x3f3f3f3f
int dp[maxn], a[maxn], lastmax[maxn];
int main()
{
int m, n;
while(scanf("%d %d",&m,&n)!=EOF)
{
memset(dp, 0, sizeof dp);
memset(lastmax, 0, sizeof lastmax);
int maxx;
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
for(int i=1; i<=m; i++) //在第i層循環中,lastmax[j]是指第j個元素前的劃分成i-1份的最大的sum
{
maxx = -inf;
for(int j=i; j<=n; j++) //要分成i組則至少需要i個數,所以j從i開始循環
{
dp[j] = max(dp[j-1]+a[j], lastmax[j-1]+a[j]);
lastmax[j-1] = maxx; //只能更新以前一個數結尾的lastmax(因爲當前數的lastmax要在下一輪迭代中要用來更新dp
//所以還必須在當前層dp更新完後更新)
maxx = max(dp[j], maxx); //該語句不可與上行語句交換位置
}
}
cout << maxx << endl; //此時maxx存儲的即爲最後一次劃分(m份)的最大值
}
return 0;
}