HDU 1003 Max Sum

ACM OJ题解目录
本题网址:https://cn.vjudge.net/problem/HDU-1003

Max Sum

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

题目大意:
  第一行输入一个整数T∈[1, 20]。
  接下来T行以一个整数N∈[1, 100000]开始,接下来N个整数a[i]∈[-1000, 1000]。
  接下来N组答案,每组固定格式外,要输出第i个序列中的最大和、子序列的起始位置、子序列的结束位置。
  注意输出两个序列之间的空行,最后一个序列后面不要输出空行~
 
分析:
  没有什么比讨论小明更有趣的事情了,没错,我的同学小明又来问我这道题了。
  他说:龙哥你看看这道题,区间求和问题,我用的线段树,居然超时了!线段树不是区间求和里很优化的一种算法了吗,这怎么也超时?
  没错,线段树是适合区间操作,但那是区间有被修改的情况下,再去查询区间和或最值,才会具有较高的效率。而像这种直接判断连续区间最大和的题型,直接贪心就好了。而且要记住,这也是典型的贪心问题。有人说用动态规划,但是这还要搞一个数组出来, 又要写状态转移方程的,没必要!
  
下面说一下贪心思想:
  一段连续的区间,如果前面部分区间和是负值,那么后面区间加上前面区间的和,一定没有不加的结果大。所以我们只需要从前到后遍历一遍即可。
  第一,记录该区间左端和右端,并时刻更新最大区间和以及区间首尾下标。
  第二,如果区间和为负值,下一次遍历,直接记录下一个值即可,不需要相加。将前面区间和丢弃,区间左右端也更新一下。
 
代码如下:

#include <iostream>
using namespace std;

int main()
{
	int t, n;
	int MAX, sum;
	int left, right, begin, end;

	scanf("%d", &t);

	for (int k = 1; k <= t; k++)
	{
		scanf("%d", &n);

		sum = MAX = INT_MIN;

		for (int i = 1, j; i <= n; i++)
		{
			scanf("%d", &j);

			//如果前面的和是负的,那么直接从后面开始取就行,因为如果你包含前面那段的和,肯定没有不包含的大
			if (sum < 0)
				sum = j, left = right = i;
			else
				sum += j, right++;

			//取最大的和与该区间
			if (MAX < sum)
				MAX = sum, begin = left, end = right;
		}

		printf("Case %d:\n%d %d %d\n", k, MAX, begin, end);

		if (k < t) puts("");
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值