HDU1024 Max Sum Plus Plus(DP动态规划 最大子串和增强版)

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20708    Accepted Submission(s): 6886


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 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
Hint
Huge input, scanf and dynamic programming is recommended.
 

Author
JGShining(极光炫影)



题目大意:

给出子串划分的集合个数,再给出子串的长度和子串的元素,求子串的和最大为多少?


解题思路:

dp[i][j]表示划分成i组,第j个元素的最大子串和,可列出状态转移方程:dp[i][j] = max(dp[i][j-1] + a[j],dp[i-1][k] + a[j]),(其中k为1~j-1),这个方程的意思是:如果子串划分的个数相等,那我们就加上下一个元素,否则如果不相等,那么就等于上一个集合的子串和加上一个元素。本题由于i和j的取值特别大,很明显二维数组肯定存不下,所以要考虑用一维数组代替二维数组,再次考虑时间复杂度,如果枚举k的话,必然超时,所以我们可以只存取上一个集合子串和的最大值,所以最后状态转移方程为dp[j] = max(dp[j-1]+a[j],pre[j-1]+a[j]),其中pre[j-1]就是上一个状态子串的最大值,也是运用了dp空间换时间的思想.

都说dp很考验编程思维和代码功底,的确如此,首先dp动态规划的确太灵活了,而且单纯写出状态转移方程有时候还不够,经常面临了超时或者超内存的风险,所以必须还要优化,有时候运用二维降一维的思路,或者是运用滚动数组降低空间复杂度,时间复杂度就不用说了,本身DP的核心思想就用保存上一次计算过的结果,避免重复计算.就本题而言前面计算过的pre数组可以直接拿来用,再次计算就没有必要了,所以灵活的变通和多练习是解决dp动态规划最核心的方法.

其中本题参考了Kuangbin大神的思想.


AC代码:

#include
#include
#include
#include
using namespace std;

const int maxn = 1000005;
int a[maxn];
int dp[maxn];
int pre[maxn];
const int inf = 0x3f3f3f3f;

int main()
{
	int m,n;
	int i,j;
	//freopen("1.txt","r",stdin);
	while(scanf("%d%d",&m,&n) != EOF)
	{
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		}
		dp[0] = 0;
		memset(pre,0,sizeof(pre));
		int Max;
		for(i=1;i<=m;i++)
		{
			Max = -inf;
			for(j=i;j<=n;j++)
			{
				dp[j] = max(dp[j-1],pre[j-1]) + a[j];
				pre[j-1] = Max;
				if(dp[j] > Max)
				{
					Max = dp[j];
				}
			}
		}
		printf("%d\n",Max);
	}
	return 0;
}

你可能感兴趣的:(动态规划,杭电(hdu)OJ题目)