zoukankan      html  css  js  c++  java
  • Max Sum(最大子串和)

    Max Sum

    Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

    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
     

     
     
    Analysis
     
      状态转移方程 dp[i] = max( dp[i-1] + a[i] , a[i] )
     
     
     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 int a[100002];
     5 
     6 main()
     7 {
     8     int T,N,kkk=1,i,j;
     9 
    10     scanf("%d",&T);
    11     while(T--)
    12     {
    13         int max,max_s,max_e,sum,sum_s;
    14         //memset
    15         printf("Case %d:
    ",kkk++);
    16 
    17         scanf("%d",&N);
    18         for(i=1;i<=N;i++)
    19         {
    20             scanf("%d",&a[i]);
    21         }
    22 
    23         max = sum = a[1];
    24         max_s = max_e = sum_s = 1;
    25 
    26         //printf("sum = %d  max = %d
    ",sum,max);
    27         for(i=2;i<=N;i++)
    28         {
    29             if(sum + a[i] < a[i])
    30             {
    31                 sum = a[i] ;
    32                 sum_s = i ;
    33             }
    34             else sum = sum + a[i] ;
    35 
    36             if(sum > max)
    37             {
    38                 max = sum ;
    39                 max_s = sum_s;
    40                 max_e = i;
    41             }
    42             //printf("sum = %d  max = %d
    ",sum,max);
    43         }
    44         printf("%d %d %d
    ",max,max_s,max_e);
    45         if(T)
    46         printf("
    ");
    47     }
    48 }
  • 相关阅读:
    oracle循环语句
    解决使用Properties读取中文乱码问题
    oracle常用& to_date()怎么转换带am pm的时间格式
    distinct 多列详解
    javascript中遍历EL表达式List集合中的值
    最近一段时间代码汇总
    JAVA基础之对象的初始化
    求解圆圈中最后剩下的数字
    删除有序链表中的重复结点
    构造二叉树,并求解树的高度
  • 原文地址:https://www.cnblogs.com/GY8023/p/4682297.html
Copyright © 2011-2022 走看看