题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024
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 S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn.
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.
题解:
假设a[i]中存放该序列第i个值
w[i][k]:前k个数分为i段,第k个数必须选
1:第k个数单独为1段
2:第k个数与前面的数连一块。w[i][k]=max(b[i-1][k-1],w[i][k-1])+a[k]
b[i][k]:在前k个数中取i段这种情况下取得的最大值
1:选第k个数
2:不选第k个数。b[i][k]=max(b[i][k-1],w[i][k])
w[i][k],b[i][i]容易求得,所以由b[i-1][k-1]>>w[i][k]>>b[i][k],只要知道b[0][k],全部都能成功求出
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
int sum[100010],a[100010],dp[2][100010]; //dp值定义2层是因为待会每次需要的时候只用提出上一次的值,每次用完都会刷新,这样节省空间,以防WA
int main()
{
int i,k,m,n,flag;
while(~scanf("%d%d",&m,&n))
{
sum[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&k);
sum[i]=sum[i-1]+k;//前i个数的和
dp[0][i]=0; //初始化
}
flag=1;
for(i=1;i<=m;i++)//循环里面算的是把k个数分成i段的最大值
{
for(k=i;k<=n;k++)//k<i时就没有意义,所以从i开始
{
if(i==k)//k个数分成k段的最大值就是sum[k]
dp[flag][k]=a[k]=sum[k];
else
{
a[k]=max(dp[1-flag][k-1],a[k-1])+sum[k]-sum[k-1];//这时候flag是上一次外层循环中的值,也就是dp[1-flag][k-1]是上一轮的值
//a[k]表示k个元素取i段,第k个数必须取时的最大值
dp[flag][k]=max(a[k],dp[flag][k-1]);
//dp[flag][k]表示在第k个数可取可不取这两种情况下取得的最大值
}
}
flag=1-flag;//flag一直在1和0中变换
}
printf("%d\n",dp[m%2][n]);//m%2是看第几轮,m为奇数flag为0,因为循环最后flag变了一次值
}
return 0;
}
PS:部分思想是看lishuhuakai的代码,ta的链接:http://blog.csdn.net/lishuhuakai/article/details/8067474