我是靠谱客的博主 隐形耳机,最近开发中收集的这篇文章主要介绍hdu 1003 求连续子数列的最大和,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

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

#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 %dn",ans,sta,end);输出的最大值是ans,不是sum因为可能最后一次加得的结果小于倒数第二次的结果。必须进行一次比较
          if(t)
               printf("n");//输出格式要注意
    
    }
    return 0;
}

最后

以上就是隐形耳机为你收集整理的hdu 1003 求连续子数列的最大和的全部内容,希望文章能够帮你解决hdu 1003 求连续子数列的最大和所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部