HDu 1024最大Mサブセグメントdp

2763 ワード

タイトル:
Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 27299    Accepted Submission(s): 9499
Problem Description
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. ^_^
 
 
Input
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
Output the maximal summation described above in one line.
 
 
Sample Input
1 3 1 2 3 2 6 -1 4 -2 3 -2 3
 
 
Sample Output
6 8
Hint
Huge input, scanf and dynamic programming is recommended.
最大連続サブセグメントを求めるのとは少し異なり、この問題はm個の連続サブセグメントのsumを求めることを要求し、sumをできるだけ大きくする.
状態遷移方程式を考慮する:f{i,j}は前のj個の要素がiセグメントに分かれた最大値を表し、 
f{i,j}=max{f{i,j-1},max{i-1,k}}+a[j],(i-1<=k
2つの決定:
-1-:  前のj要素はiセグメントに分けて最後のセグメントをaで終わる.
-2-:ajは独自に1段を占め、残りのi-1段は前k(i-1<=k
nは100 wであり、スクロール配列を用いることを考慮し、pre[j]は前のiに対応するjの最大値を保存し、dp[j]は現在計算中のiのjの最大値である.
コード:
#includeusing namespace std;const int inf=999999999;int dp[1000005],a[1000005],pre[1000005];int main(){ int n,m,i,j,k,t; while (cin>>m>>n){int maxn=-inf;t=0; memset(dp,0,sizeof(dp)); memset(pre,0,sizeof(pre)); for (i=1;i<=n;i++) scanf("%d",&a[i]);
for (i=1;i<=m;i++){ maxn=-inf;                                              //各ラウンドの開始はmaxnをfor(j=i;j<=n;j+){dp[j]=max(pre[j-1],dp[j-1])+a[j];           //更新前のラウンドの値pre[j-1]=maxnを先に使用します.                                       //ここで重要なのは、次のj計算に用いるj-1が本輪の最大値となる意味になると、概念が変わるので、以下の注釈の形式に書くことはできない.
if (maxn//pre[j]=maxn; }//for(int l=0;l<=n;l++) cout<
//cout< }
cout< }
return 0;
}

転載先:https://www.cnblogs.com/zzqc/p/6412848.html