HDU1024 Max Sum Plus Plus

本文详细解析了最大n段连续子序列和问题的解决策略,通过动态规划方法,逐步推导并实现了解决方案。示例输入包含整数m、n和一系列整数序列S1至Sn,输出为最大连续子序列和。文中还提供了具体的代码实现,方便读者理解和实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:最长n段连续子序列和

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

算法思想:

dp[i][j]保存前j个元素(包括j)分成i段最长连续子序列和

则有dp[i][j]=max(dp[i][j-1]+num[j],max(dp[i-1][t]+num[j]))     i-1<=t<j

具体思路参见最大子段和问题到最大子矩阵问题(二):最大n子段和问题详谈


#include <iostream>
using namespace std;

int *s;
int m,n;
int maxL;
int *pre,*now;
int main()
{
	freopen("C:\\in.txt","r",stdin);
	
	while(scanf("%d %d",&m,&n)!=EOF){
		s=new int[n+1];
		pre=new int[n+1];
		now=new int[n+1];
		for(int i=0;i<=n;i++){now[i]=0;pre[i]=0;}
		for(int i=1;i<=n;i++){
			scanf("%d",&s[i]);
		}
		for(int i=1;i<=m;i++){
			maxL=-0x7fffffff;
			for(int j=i;j<=n;j++){
				now[j]=(now[j-1]>pre[j-1]?now[j-1]:pre[j-1])+s[j];
				pre[j-1]=maxL;
				if(maxL<now[j])
					maxL=now[j];
			}
		}
		printf("%d\n",maxL);
		delete[] s;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值