• J


    J - 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

    //第一行代表有 t 组测试案例,问最大连续的和为多少,并输出第几位数到第几位数
    //虽然,这是一道dp水题,但我从没做过,自己写出来感觉不错,62ms 比别人的慢了一倍,应该是我用了两次一重循环吧。

     1 #include <stdio.h>
     2 
     3 #define MAXN 100005
     4 
     5 int num[MAXN];
     6 int dp[MAXN];
     7 
     8 int cmp(int a,int b)
     9 {
    10     return a>b?a:b;
    11 }
    12 
    13 int main()
    14 {
    15     int t;
    16     int n,i,Case=0;
    17     scanf("%d",&t);
    18     while (t--)
    19     {    
    20         scanf("%d",&n);
    21         int max;
    22         for (i=1;i<=n;i++)
    23         {
    24             if (i==1)
    25             {
    26                 scanf("%d",&num[i]);
    27                 dp[i]=num[i];
    28                 max=i;
    29                 continue;
    30             }
    31             scanf("%d",&num[i]);
    32             dp[i]=cmp(num[i],dp[i-1]+num[i]);
    33             if (dp[i]>dp[max]) max=i;
    34         }
    35         int s=max;
    36         for (i=max;i>=1;i--)
    37         {
    38             if (dp[i]>=0)
    39                 s=i;
    40             if (dp[i]<0)
    41                 break;
    42         }
    43         printf("Case %d:
    ",++Case);
    44         printf("%d %d %d
    ",dp[max],s,max);
    45         if (t!=0) printf("
    ");
    46     }
    47     return 0;
    48 }
    View Code
     
  • 相关阅读:
    docker
    20192413宗俊豪汇编语言程序设计学习总结
    20192413宗俊豪 202120222 《网络与系统攻防技术》实验一实验报告
    测试部门目标
    Ubuntu安装/配置Nvim+coc.vim
    nginx反向代理nexus私服
    数据库级别判断数据重复
    使用注解管理spring bean生命周期
    合并两个有序链表
    如何查找对应的JVM参数
  • 原文地址:https://www.cnblogs.com/haoabcd2010/p/5749585.html
Copyright © 2020-2023  润新知