ACM1003: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
----------------------------------------------------------------------------------------------------------------
 
/*
设a[i]为和最大序列的起点,则如果a[i]是负的,那么它不可能代表最优序列的起点,因为任何包含a[i]作为起点的子序列都可以通过a[i+1]作起点而得到改进。
类似的,任何负的子序列也不可能是最优子序列的前缀。
注意:如果全为负值,则取序列最大值。
*/
 
#include <stdio.h>  
#define SIZE 100100

int main() {
	//数据个数,数组长度。
	int n, m;
	//序列
	int a[SIZE];
	int i, j, k;
	long long sum;
	long long max;
	int leftBorder, rightBorder, tempBorder;

	//freopen("F:\\input.txt","r",stdin);
	scanf("%d", &n);
	for (i = 0; i < n; i++)
	{
		sum = 0;
		max = -1001;
		memset(a, 0, sizeof(a));
		leftBorder = rightBorder = tempBorder = 0;
		scanf("%d", &m);
		for (j = 0; j < m; j++)
		{
			scanf("%d", &a[j]);
			sum += a[j];
			//如果当前和大于目前的最大和,则将sum设为最大和,并且更新边界
			if (sum > max)
			{
				max = sum;
				leftBorder = tempBorder;
				rightBorder = j;
			}
			//如果当前和小于0,则当前序列不可能为最优序列的起点,重置和与边界
			if (sum < 0)
			{
				sum = 0;
				tempBorder = j + 1;
			}


		}
		printf("Case %d:\n", i + 1);
		printf("%lld %d %d\n",max, leftBorder + 1, rightBorder + 1);
		if (i != (n - 1))
			printf("\n");
	}
	//freopen("con", "r", stdin);
	//system("pause");
	return 0;
}

  

 
 
posted @ 2019-03-11 19:18  烈焰蔷薇  阅读(139)  评论(0编辑  收藏  举报