m段的最大和(動態規劃)
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
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
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
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段,並求出這m段的總和。
我們之前做過最大子段和,也就是隻有一段序列用的是一維dp,而這道題我們不光要考慮每個數字的位置,還要考慮段數。
dp[i][j] 前j個數分為i段的和的最大值。
我們在dp時遇到a[k]考慮的無非兩種情況(選)or(不選),然而在(選)的時候又有兩種情況(自成一段)or (與前面的段合在一起)。
根據(選)a[k]的時候的兩種情況,我們要設兩個陣列b[i][k](表示在前k個數中取i段這種情況下取得的最大值),w[i][k](選了a[k-1]時的最大值,也就是與前段結合時)。當前狀態 w[i][k]=max(b[i-1][k-1],w[i][k-1])+a[k];
現在(選)的情況全部考慮完了,當前情況
的最大值 1.選,2 不選 b[i][k]=max(b[i-1][k-1],w[i][k]);
也就是 b[i][k]=max(b[i][k-1],max(b[i-1][k-1],w[i][k-1])+a[k])
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#define LL long long
#define ULL unsigned long long
#define mod 1000000007
#define INF 0x7ffffff
using namespace std;
const int Maxn=1000001;
int sum[Maxn],w[Maxn],dp[2][Maxn];
int main()
{
int n,m;
while(~scanf("%d%d",&m,&n)){
int i,k;
sum[0]=0;
for(i=1;i<=n;i++){
scanf("%d",&k);
sum[i]=sum[i-1]+k;
dp[0][i]=0;
}
int t=1;
for(i=1;i<=m;i++){
for(k=i;k<=n;k++){
if(i==k)
dp[t][k]=w[k]=sum[k];
else{
w[k]=max(dp[1-t][k-1],w[k-1])+sum[k]-sum[k-1];
dp[t][k]=max(dp[t][k-1],w[k]);
}
}
t=1-t;
}
printf("%d\n",dp[m%2][n]);
}
return 0;
}
對於t的交替變換 是因為b[i][k]=max(b[i][k-1],max(b[i-1][k-1],w[i][k-1])+a[k])狀態轉移中 i的變換隻有i和i-1 我們用 0 1 代替即可。