Max sum。。。。。hdu oj----1003

Max sum

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


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
 1 #include<stdio.h>
 2 int main()
 3 {
 4     int T,N,count=0,a[100010];
 5     scanf("%d",&T);
 6     while(T--)
 7     {
 8         count++;
 9         int start,s,end,e,max,sum,i;
10         scanf("%d",&N);
11         for(i=1;i<=N;i++)
12         scanf("%d",&a[i]);
13         /*此题主要意思是记录任意几个连续数字的和最大,并记录开始与结束的位置*/
14         for(sum=max=a[1],s=e=start=end=1,i=2;i<=N;i++)
15         {     /*开始与结束的位置是变化的*/
16             if(sum<0){sum=0;start=i;end=i-1;}
17             /*第一种情况,sum变为负数时,sum归零处理不会影响后面的判断,起始值变为i,末尾值变为i-1*/
18             sum+=a[i]; end++;
19             if(sum>max){s=start;e=end;max=sum;}
20             /*第二种情况,s 记录当前的起始值,e 记录当前的末位置*/
21         }
22         printf("Case %d:\n",count);
23         printf("%d %d %d\n",max,s,e);
24         if(T>0) printf("\n");
25     }
26     return 0;
27 }
View Code
posted on 2013-07-25 16:00  yun_  阅读(267)  评论(0编辑  收藏  举报