zoukankan      html  css  js  c++  java
  • 动态规划——A 最大子段和

    A - 最大子段和
    Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
    Submit Status

    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
     
    解题思路:

    题目意思:最大子段和是要找出由数组成的一维数组中和最大的连续子序列。比如{5,-3,4,2}的最大子序列就是 {5,-3,4,2},它的和是8,达到最大;而 {5,-6,4,2}的最大子序列是{4,2},它的和是6。看的出来了,找最大子序列的方法很简单,只要前i项的和还没有小于0那么子序列就一直向后扩展,否则丢弃之前的子序列开始新的子序列,同时我们要记下各个子序列的和,最后找到和最大的子序列

     
    程序代码:
     1 #include <cstdio>
     2 using namespace std;
     3 const int N=100100;
     4 int a[N],n,b[N],num[N];
     5 long long sum;
     6 int q;
     7 int main()
     8 {
     9     int t,Case=0;
    10     scanf("%d",&t);
    11     while(t--)
    12     {
    13         scanf("%d",&n);
    14         for(int i=1;i<=n;i++)
    15                 scanf("%d",&a[i]);
    16         b[1]=a[1];num[1]=1;
    17         for(int i=2;i<=n;i++)
    18         {
    19             if(b[i-1]>=0)
    20                {
    21                   b[i]=b[i-1]+a[i];
    22                   num[i]=num[i-1];
    23                }
    24              else
    25              {
    26                  b[i]=a[i];
    27                  num[i]=i;
    28              }
    29         }
    30         sum=b[1];q=1;
    31         for(int i=2;i<=n;i++)
    32         {
    33             if(b[i]>sum)
    34             {
    35                 sum=b[i];
    36                 q=i;
    37             }
    38         }
    39         printf("Case %d:
    ",++Case);
    40         printf("%lld %d %d
    ",sum,num[q],q);
    41         if(t) printf("
    ");
    42     }
    43     return 0;
    44 }
    View Code
    版权声明:此代码归属博主, 请务侵权!
  • 相关阅读:
    ABAP 动态内表构建 Dynamic internal table
    RFC权限分配
    ERP从业来的总结
    WORD中插入VISIO图形,打印乱码解决
    SAP中程序间的相互调用,SUBMIT关键字的用法
    SDva01的屏幕增强
    STL中的binder
    C++中的new
    C++数组中多态问题分析
    Gdiplus中实现双Buffer绘图
  • 原文地址:https://www.cnblogs.com/www-cnxcy-com/p/4721852.html
Copyright © 2011-2022 走看看