Hdoj 1003

原题链接

描述

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.

输入描述

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).

输出描述

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.

样例输入

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

样例输出

Case 1:
14 1 4

Case 2:
7 1 6

思路

最大连续子列和问题,典型的动态规划。需要注意的是格式问题。
首先找到状态转移方程sum[i] = max{sum[i-1] + a[i-1], a[i-1]},维护起始值即可确定开始点和结束点。
实际上,也不需要开数组,sum和a随时变化也可以。这样能将空间复杂度降到O(1),而时间复杂度是O(n)。

代码

#include <bits/stdc++.h>   
using namespace std;  

int main()
{
	int n; cin >> n;
	for(int ii = 0; ii < n; ii++)
	{
		int num; cin >> num;
		int f = 0, l = 0, t = 0;
		int max, sum;
		cin >> max; sum = max;
		for(int i = 1; i < num; i++)
		{
			int a;
			cin >> a;
			if(sum >= 0)
			{
				sum += a;
			}
			else
			{
				sum = a;
				t = i;
			}
			if(sum > max)
			{
				max = sum;
				f = t;
				l = i;
			}
		}
		printf("Case %d:\n%d %d %d\n", ii + 1, max, f + 1, l + 1);
		if(ii < n - 1) printf("\n");
	}
}
posted @ 2018-01-27 22:06  HackHarry  阅读(148)  评论(0编辑  收藏  举报