Max Sum (动态规划)

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

这道题真的是做的有点难受了,刚开始用的一种动态转移方程的一种算法可以的出来子段最大和,但是卡在了如何求起点终点的问题上,因为使用dp[i]=max(0,dp[i-1]+a[i])这个方程的话我们很难去处理出现全部都是或者部分负数的情况,虽然样例都是可以过的,所以只能去转变思路,没有用动态转移方程做,这道题WA了10遍,格式错误了4遍,详细内容看代码,容易出错的地方都有标注。

#include<iostream>
#include<algorithm>
using namespace std;
int T, n;
int i, num;
int main()
{
	cin >> T;
	num = 0; //Case后面的num需要输出次数
	while (T--)
	{
		int sum = 0, summax = -10000, k = 1, end = 1, start = 1, a[100001]; //sum=0,summax=-10000方便处理负数的情况,k=1为了记录起点
		num++;
		cin >> n;
		for (i = 1; i <= n; ++i)
		{
			cin >> a[i];
		}
		for (i = 1; i <= n; ++i)
		{
			sum += a[i]; //累加
			if (summax < sum) //summax记录最大的和
			{
				summax = sum;
				start = k; //倘若不出现sum<0的情况,起点一直是1
				end = i; //计算到哪summax为最大和,end就是结尾
			}
			if (sum < 0) //出现sum<0的情况
			{
				sum = 0; //重新开始计算
				k = i + 1; //使k为i+1,重新开始赋值给start
			}
		}
		cout << "Case" << " " << num << ":" << endl;
		cout << summax << " " << start << " " << end << endl; //这里的endl不要混淆题目意思,不管是不是最后一组数据都要加!
		if (T != 0)
			cout << endl; //这里容易出现格式问题!!
	}
	return 0;
}
发布了90 篇原创文章 · 获赞 15 · 访问量 3149

猜你喜欢

转载自blog.csdn.net/qq_43656233/article/details/90739836