• HDU 1003 Max Sum(最大连续子序列和)


    Max Sum

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 63276    Accepted Submission(s): 14433

    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

    Author

    Ignatius.L

     解题报告:典型的动态规划,就是求最大连续子序列和的并记录起始位置!

    代码如下:

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    const int N = 100010;
    int a[N],pos[N],f[N],ans;//pos[]数组记录起始位置,f[]数组记录和
    int main()
    {
    int t,n,i,k,j,ans,begin,end;
    //freopen("1001.txt","r",stdin);
    scanf("%d",&t);
    k=0;
    for(j=1;j<=t;j++)
    {
    scanf("%d",&n);
    for(i=1;i<=n;i++)//初始化
    {
    scanf("%d",&a[i]);
    pos[i]=i;
    }
    f[1]=a[1];
    for(i=2;i<=n;i++)
    {
    if(a[i]+f[i-1]>=a[i])
    {
    pos[i]=pos[i-1];//关键!起始位置和前一个相同
    f[i]=a[i]+f[i-1];
    }
    else
    {
    f[i]=a[i];
    }
    //printf("%d %d\n",i,f[i]);
    }
    ans=-9999;
    for(i=1;i<=n;i++)//遍历一回求最大
    {
    if(ans<f[i])
    {
    ans=f[i];
    begin=pos[i];
    end=i;
    }
    }
    printf("Case %d:\n",++k);
    printf("%d %d %d\n",ans,begin,end);
    if(k!=t)//最后一行没有空格!
    {
    printf("\n");
    }
    }
    return 0;
    }



  • 相关阅读:
    C# 关键字 virtual、override和new的用法
    架构技术及架构要素总结【转】
    vue文件目录结构
    vue项目中,如何对static文件夹下的静态文件添加时间戳,以达到清除缓存
    webpack中关于require与import的区别
    vue 根据下拉框动态切换form的rule
    el-select 根据value查询其对应的label值
    web前端项目规范
    JavaScript 编码规范
    HTML 编码规范
  • 原文地址:https://www.cnblogs.com/lidaojian/p/2265226.html
Copyright © 2020-2023  润新知