• HDU 1003 Max Sum


    Max Sum

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


    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
     
    解题心得:
      这个题是一个简单地动态规划题,题意:输入n个数,求它的最大的子序列和。首先写出状态转移方程: sum[i]=max{sum[i-1]+a[i],a[i]}。
      s数组是记录开始位置,每当sum加上一个a[i],值小于0的时候,s取用新的值。ans是记录结束位置,每当sum加上一个a[i],值大于等于0的时候,更新一下。
        我又在格式问题上出错了,以后要更加注意格式问题,最后一行不需要换行!
      也可以参考这个人的思路,http://blog.csdn.net/code_pang/article/details/7772200,通过枚举发现的规律。
     
    最后是代码:
    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    
    int main()
    {
        int t;
        int n;
        int a[100005];//存储序列
        int sum[100005];//存储以每个数为结尾的子序列和
        int s[100005];//存储开始位置
        int ans;//结束位置
        scanf("%d",&t);
        for(int i=1;i<=t;i++){
            scanf("%d",&n);
            for(int i1=0;i1<n;i1++){
                scanf("%d",&a[i1]);
            }
            ans=0;
            sum[0]=a[0];
            s[0]=0;
            for(int j=1;j<n;j++){
                if(sum[j-1]>=0){
                    sum[j]=sum[j-1]+a[j];
                    s[j]=s[j-1];
                }else{
                    sum[j]=a[j];
                    s[j]=j;
                }
                if(sum[ans]<sum[j])
                    ans=j;
            }
            if(i<t){
                printf("Case %d:
    %d %d %d
    ",i,sum[ans],s[ans]+1,ans+1);
                printf("
    ");
            }else{
                printf("Case %d:
    %d %d %d
    ",i,sum[ans],s[ans]+1,ans+1);
            }
        }
        return 0;
    }
    View Code
      
  • 相关阅读:
    结算凭证中委托付款部分sql
    各公司年资金归集汇总sql
    通过开户银行账号查询客商名称 sql
    TRIGGER_15.8.3BACKUP
    备份触发器:ADDC3
    sql查询单个银行账号重复
    待研究:insert客商账户触发器增加条件提示为空
    sql:劳务统计各分公司管理费用明细合计(等同汇总报表)
    【ASP.NET程序员福利】打造一款人见人爱的ORM(二)
    【ASP.NET程序员福利】打造一款人见人爱的ORM(一)
  • 原文地址:https://www.cnblogs.com/TWS-YIFEI/p/5590532.html
Copyright © 2020-2023  润新知