• 2015 HUAS Summer Trainning #5 A


    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
     
    题目大意:给你N个数,要你求最大的子段和(连续的)。
     
    解题思路:
     1 for(i=1;i<=n;i++)
     2         {
     3             cin>>d;
     4             t+=d;
     5             if(t>max)
     6             {
     7                 start=k;
     8                 end=i;
     9                 max=t;
    10             }
    11             if(t<0)
    12             {
    13                 t=0;
    14                 k=i+1;
    15             }
    16         }
    View Code

    每个数都加一次,遇到大的就储存它的起点和终点。当和小于0时,统计和的那个变量初始化为0。

    代码:

     1 #include<iostream>
     2 using namespace std;
     3 int main()
     4 {
     5     int T,i,d,p,start,end,k,t,max;
     6     int n;
     7     cin>>T;
     8     d=0;
     9     p=0;
    10     while(T--)
    11     {
    12         cin>>n;
    13         max=-9999;
    14         start=end=k=1;
    15         t=0;    
    16         for(i=1;i<=n;i++)
    17         {
    18             cin>>d;
    19             t+=d;
    20             if(t>max)
    21             {
    22                 start=k;
    23                 end=i;
    24                 max=t;
    25             }
    26             if(t<0)
    27             {
    28                 t=0;
    29                 k=i+1;
    30             }
    31         }
    32         cout<<"Case "<<++p<<":"<<endl;
    33         cout<<max<<" "<<start<<" "<<end<<endl;
    34         if(T)
    35             cout<<endl;        
    36     }
    37     return 0;
    38 }
    View Code
     
  • 相关阅读:
    发邮件遇到 Failure sending mail.The remote name could not be resolved: 'www.youdomain.com' 问题的解决方法
    machine.config, inetinfo.exe, aspnet_wp.exe, aspnet_state.exe这些文件的作用于位置.
    IIS的变迁(IIS3, IIS4, IIS5, IIS6, IIS7)
    精简代码 (转)
    新年第一帖——元旦这天骑车迷路了
    我是月亮,也想做那天上的太阳
    记几点吧
    谈谈电影
    闺蜜
    大气
  • 原文地址:https://www.cnblogs.com/huaxiangdehenji/p/4732454.html
Copyright © 2020-2023  润新知