HDU 1024 Max Sum Plus Plus (经典DP)
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
题意:
在n个数中选出m组数, 每组连续且不能相交, 求出最大的各组数的和
思路:
正常来说动态规划基本决策就是取与不取,这里多了组数的考虑,因此有三种决策:
若dp[i][j]表示前j个数取i组的最大值,则第j个数可以加入上一组数的队尾,或者不取,或者加入新一组的队头,即有:
dp[i][j]=max (dp[i][j−1], dp[i][j−1 ]+ a[j] , dp[i−1][k] + a[j] )(0<k<j))
分别对应前i组不取第j个数,前i组取第j个数,将第j个数作为新一组的开头
可以发现对于dp[i][j]的状态都只跟上一层的状态相关, 如果max(dp[i−1][k]+a[j])(0<k<j)) 可以用另一个数组f[j]来维护,那么dp数组可以优化为一维,用一维数组来滚动, 顺序不变
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 1<<30
using namespace std;
const int manx=1e6+5;
typedef long long ll;
int a[manx],dp[manx],f[manx];
int main()
{
int n,m;
while(scanf("%d%d",&m,&n)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int maxx;
memset(dp,0,sizeof(dp));
memset(f,0,sizeof(f));
for(int i=1;i<=m;i++)
{
maxx=-inf;
for(int j=i;j<=n;j++)
{
dp[j]=max(dp[j-1]+a[j],f[j-1]+a[j]); //f数组记录的是这一组之前最大的DP
f[j-1]=maxx;
maxx=max(dp[j],maxx);
}
}
printf("%d\n",maxx); //注意这题输出不再是dp[n],第n个数可取可不取
}
return 0;
}