您的位置:首页 > 其它

HDU 1024:Max Sum Plus Plus 经典动态规划之最大M子段和

2015-10-26 15:42 369 查看


Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 21336 Accepted Submission(s): 7130



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.


具体解释见代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;

#define maxn 1000002
#define minn -1*(1e9+7)

int n, m;
int dp[maxn], b[maxn], val[maxn];

int main()
{
	//freopen("i.txt","r",stdin);
	//freopen("o.txt","w",stdout);
	
	int i, j;
	int res;
	while (scanf("%d%d", &m, &n) != EOF)
	{
		for (i = 1; i <= n; i++)
		{
			scanf("%d", val + i);
		}
		memset(dp, 0, sizeof(dp));
		memset(b, 0, sizeof(b));
		
		//dp[i][j]表示i个数分为j组且在选取了第i个数的前提下的最大值
		//dp[i][j]=max(dp[i-1][j]+a[j],max(dp[0][j-1]~dp[i-1][j-1])+a[j])
		//dp[x]表示第i轮的dp[x][i],即表示x个数时分成i个组的最大值
		//b[x]表示上一轮所有的最大值,即第j轮时,b[x]=max(dp[0][j-1]~dp[x-1][j-1])
		for (j = 1; j <= m; j++)
		{
			res = minn;
			for (i = j; i <= n; i++)
			{
				//表示dp[j][i]只有两种可能来源,一个是dp[j-1][i]+val[j],一个是max(dp[0][j-1]~dp[i-1][j-1])+a[j]
				dp[i] = max(dp[i - 1] + val[i], b[i - 1] + val[i]);
				b[i - 1] = res;
				res = max(res, dp[i]);
			}
		}
		printf("%d\n", res);
	}
	//system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: