Max Sum--hdoj 1003 dp

Max Sum

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


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
 



/*找出一个数组中和最大的一串数字,求和并输出起点和终点,简单的dp,一个数字一个数字开始加
找到小于0的话就重新开始找,否则就继续加,开始时想用01背包做,但是发现全部的数字加起来可能是
负数,这样的话01背包就没办法列出所有的情况,并且起点和终点也不好记录*/
#include<stdio.h>
#include<string.h>
int a[100010];
int main()
{
	int max,b,e,t,n,sum;
	int Case=1;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		memset(a,0,sizeof(a));
		for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
		int k=1;
		int max=0,flog=0;
		sum=b=e=0;
		for(int j=1;j<=n;j++)
		{
			if(a[j]>0)
			flog=1;//如果数组中没有一个数大于0,那么就找出最大的负数 
			sum+=a[j];
			if(sum<0)
			{
				sum=0;
				k=j+1;//如果sum<0,就让sum=0重新开始加 
			}	
			if(sum>max)
			{
				max=sum;//找到比max大的和就开始替换 
				b=k;
				e=j;
			}
		}
		if(flog==0)
		{
			max=a[1];
			b=1,e=1;
			for(int j=2;j<=n;j++)
			if(max<a[j])
			{
				max=a[j];
				b=j;e=j;
			}
		}
		printf("Case %d:\n",Case++);
		printf("%d %d %d\n",max,b,e);
		if(t>=1)
		printf("\n");
	}
	return 0;
}
 
posted @ 2015-09-09 20:35  上弦月307  阅读(111)  评论(0编辑  收藏  举报