hdu 1003 求连续子数列的最大和

来源:互联网 发布:linux dhcp分配主机名 编辑:程序博客网 时间:2024/06/09 19:03
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

题意:求一个数组,连续子数列的最大和,以及它的开始点和结束点

#include<stdio.h>
int a[1000001];
int main()
{
    int t,k=1,m,i;
    scanf("%d",&t);
    while(t--)
    {
          int sta,end,st=1,en,sum=0,ans=-999999999;//一定定义在while里面,否则多组数据时会出错
         scanf("%d",&m);
         for(i=1;i<=m;i++)
           scanf("%d",&a[i]);
         for(i=1;i<=m;i++)
         {
          if(sum>=0)
                    {
                       sum+=a[i];en=i;     //因为加一个负数一定是在变小,所以只有大于0时才进行   
                    }
          else {
                   sum=a[i];
                   st=i;
                   en=i;
               }
          if(sum>ans)
                    {
                         end=en;//这里全部是最后要输出的符合题意的结果
                         sta=st;
                         ans=sum;                         
                    }
          }
          printf("Case %d:\n",k++);
          printf("%d %d %d\n",ans,sta,end);输出的最大值是ans,不是sum因为可能最后一次加得的结果小于倒数第二次的结果。必须进行一次比较
          if(t)
               printf("\n");//输出格式要注意
    
    }
    return 0;
}

0 0