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(im, 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段,并求出这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 代替即可。