ACM最大子串和问题

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
解题思路:
题目大意就是给定一串数字,要我们求这串数字的连续的数字之和的最大值,同时我们还需要给出是哪一段数字是最大子串。大问题是求出总序列的最大和,而每个数都有加到前面作为前面已经加好的和的增量和自己独立成为一个“最大和”的选择,在这两个选择中的最大和就是局部的最大和,而保存好第一个最大和,将整个序列的所有局部最大和都求解出来,就能得到全列的最大和
程序代码:
#include <iostream>
using namespace std;
int main()
{
	int t,k=0;
	cin>>t;
	while(t--)
	{
		int n,max,sum,c,s,e,x;
		cin>>n;
		for(int i=1;i<=n;i++)
		{
			cin>>c;
			if(i==1)//初始化
			{
				sum=max=c;//max中保存的是最大的和,sum中保存的是当前的和,
				s=e=x=1;//s记录的是最大子串和的起初位置,e记录的是最大子串和的结束位置,s是一个中间变量
			}
			else
			{
				if(c>sum+c)//如果之前存储的和加上现在的数据比现在的数据小,就把存储的和换成现在的数据,反之就说明数据在递增,可以直接加上 
				{
					sum=c;
					x=i;//预存的位置要重置 
				}
				else
					sum=sum+c;
			}
			if(max<sum)//跟之前算出来的最大和进行比较,如果大于,位置和数据就要重置
			{
				max=sum;
				s=x;
				e=i;
			}
		}
		cout<<"Case "<<++k<<":"<<endl;
		cout<<max<<" "<<s<<" "<<e<<endl;
		if(t)
			cout<<endl;
	}
	return 0;
}

 

 
 
原文地址:https://www.cnblogs.com/xinxiangqing/p/4719167.html