HDU 1003 Max Sum

来源:互联网 发布:手机版组态软件 编辑:程序博客网 时间:2024/04/28 02:45

Max Sum

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


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 

Author
Ignatius.L
求最大的子序列,过程中维护最大值即可,注意输出格式。
AC代码:
#include <stdio.h>#include <stdlib.h>int main(){    int t,n,temp,a,max,last,first,c=0,sum,i,b;    scanf("%d",&t);    b=t;    while(t--)    {        scanf("%d",&n);        max=-1005;sum=0;temp=1;first=0;last=0;        for(i=0; i<n; i++)        {            scanf("%d",&a);            sum+=a;            if(sum>max)            {                max=sum;                first=temp;                last=i+1;            }            if(sum<0)//若子序列的和小于零并且加上了下一个数,那么肯定会使下一个数变小,则将sum归零,重新计算最大值。            {                sum=0;temp=i+2;            }        }        printf("Case %d:\n%d %d %d\n",++c,max,first,last);        if(c!=b)//注意输出格式        {            printf("\n");        }    }    return 0;}

0 0