HDU1003 最大连续子序列

Max Sum

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


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
 
 

【题意】

  给定一个序列a[1],a[2],a[3],.....,a[n],来计算子序列的最大和。例如,给定序列(6,-1,5,4,-7),这个序列中的最大和是 6 +(-1)+ 5 + 4 = 14。

  输入的第一行包含一个整数T(1<=T<=20),它表示测试用例的数量。然后是T行,每一行以N开头(1<=N<=100000),然后是N个整数(所有整数都在-1000到1000之间)

  对于每个测试用例,输出两行。第一行是“Case #:”,#表示测试用例的数量。第二行包含三个整数,序列中的最大和,子序列的起始位置,子序列的结束位置。如果有多个结果,输出第一个。在两种情况之间输出空行。

【代码】

#include <stdio.h>
#include <stdlib.h>
int main(){
    int i,j,n,t;
    scanf("%d",&t);
    for(i=1;i<=t;i++){
        int *a,first=0,last=0,sum=0,tmp=1,max=-1001;
        scanf("%d",&n);
        a=(int*)malloc(n*sizeof(int));
        for(j=0;j<n;j++){
            scanf("%d",&a[j]);
            sum += a[j];
            if(sum>max){
                max=sum;
                first=tmp;
                last=j+1;
            }
            if(sum<0){
                sum=0;
                tmp=j+2;
            }
        }
        printf("Case %d:
%d %d %d
",i,max,first,last);
        if(i!=t)printf("
");
        a=NULL;
    }
    return 0;
} 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/cruelty_angel/p/10915444.html