HDU1003 MAXSUM

Problem Description

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

Input

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

Output

For each testcase, you should output two lines. The first line is "Case #:", #means the number of the test case. The second line contains three integers, theMax Sum in the sequence, the start position of the sub-sequence, the endposition of the sub-sequence. If there are more than one result, output thefirst 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

这道题目运用了动态规划的思想,刚开始解题的时候用了3重循环,果断超时。

后来看了正确的解法,确实很巧妙自己敲了几遍,大概明白了其中的意思。

int main()
{
	int T;
	cin>>T;
	int MAX=0,n,temp,now,subscript1,subscript2,i,x;
	int cnt=0;
	while(T--)
	{
		cin>>n>>temp;//输入每组数据个数n和第一个数
		now=temp;//对应的变量进行初始化
		MAX=temp;
		subscript1=1;
		subscript2=1;
		x=1;
		for(i=2;i<=n;i++)
		{
			cin>>temp;
			if(now+temp<temp)//条件满足后,相当于开辟了一个新的子串继续运算
			{
				now=temp;//now记录着符合要求子串最左端的数字
				x=i;//x记录子串最左端数字的下标
			}
			else
				now+=temp;//只要满足now+temp<temp,就把当前读入的数据增加到now中,注意now可能经过此次操作会变小,但是没有关系
			if(now>MAX)//这一条件使MAX保存的始终是最大值,决定是不是要改变子串的位置
			{
				MAX=now;
				subscript1=x;
				subscript2=i;
			}
		}
		cnt++;
		cout<<"Case "<<cnt<<":"<<endl<<MAX<<" "<<subscript1<<" "<<subscript2<<endl<<endl;
	}
	return 0;
}

算法的第一个if else 语句的作用是找,找出可能连续和最大的子串,一旦now+temp<temp,就是说你输入的这个数不在满足连续子串和最大了,就开始查找新的子串。
第二个if 判断就是从你找出的子串中找出最大的,并记录位置。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值