HDU 1003 NBUT 1090 Max Sum(最大子段和)

题目:

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

这个题目就是求最大子段和。

list就是每个数,start[i] 是以 i 结尾的最大字段和的开始下标。

和一般的说法的略有区别的地方是,它要输出最左边的子段。

这就有2个地方要注意,第一,以 i 结尾的最大字段和的开始下标可能有多个,start[i] 必须取最左边的那个。

第二,即使在“start[i] 必须取最左边的那个”这个前提下,最大字段和还是可能有很多个,这时是需要取最左边的。

代码:

#include<iostream>
using namespace std;

int list[100001];
int start[100001];

int main()
{
	int cas;
	int n;
	cin >> cas;
	for (int i = 1; i <= cas;i++)
	{
		cin >> n;
		list[0] = -1;
		start[1] = 1;
		for (int i = 1; i <= n; i++)
		{
			cin >> list[i];
			if (list[i - 1] >= 0)
			{
				list[i] += list[i - 1];
				start[i] = start[i - 1];
			}
			else start[i] = i;
		}
		int maxs = list[1], key = 1;
		for (int i = 2; i <= n; i++)
		{
			if (maxs < list[i])
			{
				maxs = list[i];
				key = i;
			}
		}
		cout << "Case " << i << ":" << endl << maxs << " " << start[key] << " " << key << endl;
		if (i < cas)cout << endl;
	}
	return 0;
}

你可能感兴趣的:(HDU 1003 NBUT 1090 Max Sum(最大子段和))