hdoj1003 DP

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 306494    Accepted Submission(s): 72850

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

分析:

第一次是用暴力解法,时间复杂度为O(n*n),果然TLE了!!

上网查了之后才明白这是个动态分配的题。大体思路是依次遍历data数组,若sum>=0,则令sum+=data[i],否则sum=data[i],然后比较sum和max,若sum>max,则令max=sum,并修改相应的子列起初下标start和截至下标end。这样一次遍历下来之后就找到了和最大的子列。时间复杂度为O(n)。

注意输出格式,输出每个Case的结果后空一行(除最后一个Case)。

下面给出AC代码。

#include<cstdio>
using namespace std;

int main(){
	int T,cas=0;
	int data[100005];
	scanf("%d",&T);                 //输入T(测试用例个数)
	while(T--){
		int max=-1e8,sum=0,start=0,end=0,s=0;   //初始时给max一个很小的值
		printf("Case %d:\n",++cas);
		int n;
		scanf("%d",&n);            //输入序列大小
		for(int i=0;i<n;i++){
			scanf("%d",&data[i]);
			if(sum>=0){
				sum+=data[i];
			}
			else{
				sum=data[i];
				s=i;               //s为当前序列的起始下标
			}
			if(sum>max){
				max=sum;
				start=s;
				end=i;
			}
		}
		printf("%d %d %d\n",max,start+1,end+1);
		if(T!=0)
			printf("\n");
	}
	return 0;
}

 

posted @ 2018-12-08 23:58  Frank__Chen  阅读(124)  评论(0编辑  收藏  举报