HDU-1003-Max Sum【DP】

本文解析了一道经典的编程题目——最大子序列和问题。通过动态规划方法寻找序列中具有最大和的连续子序列,并输出该子序列的起始和结束位置。提供了完整的代码实现及样例输入输出。

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

题目链接:点击打开链接

Max Sum

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


Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
 

Sample Input
  
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
 

Sample Output
  
Case 1: 14 1 4 Case 2: 7 1 6

大意: 
  给出一个序列,求出序列中连续的数的和的最大值并输出连续数列中首尾的位置,比如6 -1 5 4 -7 中6-1+5+4=14为连续数列中和最大的。
  输入:
    先输入t,表示t组测试数据;
    每组测试数据第一个数为序列的个数;
  输出:
    输出要求的最大和,和求出的序列的首尾位置。
题解:竟然不会记录元素首尾的位置,唉,看了别人的思路

用数组 dp [ i ] 记录以 a [ i ] 结尾的最大连续子序列,然后只需找出 dp [ i ] 的最大值就行了

对于序列中的元素 a [ i ] 只有两种情况:

1、a [ i ] 成为一个子序列的终点,就是跟 以a [ i-1]结尾的子序列接上;这时: dp [ i ] = dp [ i-1] + a [ i ]

2、a [ i ] 成为一个新子序列的起点;这时: dp [ i ] = a[ i ];

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX=1e5+10;
int n;
int a[MAX];
int dp[MAX]; // 表示以 a[i] 结尾的最大子序列 
bool flag=0;
int main()
{
	int t,text=0;
	scanf("%d",&t);
	while(t--)
	{
		memset(a,0,sizeof(a));
		memset(dp,0,sizeof(dp));
		int start,end;
		int ans=-9999999;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]); 
			dp[i]=max(a[i],dp[i-1]+a[i]);
			if(ans<dp[i])
			{
				ans=dp[i];
				end=i;
			}
		}
		int sum=0;
		for(int i=end;i>=1;i--)
		{
			sum+=a[i];
			if(sum==ans)
			{
				start=i;
			}
		}
		if(flag)	printf("\n");
		printf("Case %d:\n%d %d %d\n",++text,ans,start,end);
		flag=1;
		//if(t)	printf("\n"); 第一次见这样的换行格式 就是单纯的记录一下这样的换行格式 
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值