您的位置:首页 > 其它

HDU 1024 Max Sum Plus Plus(DP)

2016-03-26 17:26 387 查看
题意:给你一串序列,问你把这个序列分成m组的最大连续和为多少

思路:最大连续和的升级版,我们令dp[i][j]为前j个数组成i个组的最大连续和,显然有两种决策,第j个数要么包含在i组中,要么另开一组,那么转移方程即为dp[i][j]=max(dp[i][j-1]+a[j],max(dp[i-1][k])+a[j]); (0<k<j),因为这里n多达一百万并且留意到第一维的转移其实只有需要一个dp[i-1][k],那么我们直接另开一个数组来表示即可。

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 1000005
#define LL long long
const int inf = 0x3f3f3f3f;
int cas=1,T;
int dp[maxn];
int pre[maxn];
int a[maxn];
int main()
{
int n,m;
while (scanf("%d",&m)!=EOF)
{
scanf("%d",&n);
for (int i = 1;i<=n;i++)
{
scanf("%d",&a[i]);
dp[i]=0;
pre[i]=0;
}
dp[0]=0;
pre[0]=0;
int maxx=-inf;
for (int i = 1;i<=m;i++)
{
maxx=-inf;
for (int j=i;j<=n;j++)
{
dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);
pre[j-1]=maxx;
maxx=max(maxx,dp[j]);
}
}
printf("%d\n",maxx);
}
//freopen("in","r",stdin);
//scanf("%d",&T);
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}


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(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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: