• 动态规划1001


    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.<br>
     
    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).<br>
     
    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.<br>
    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
    解题思路:
    给定一串数字,求其中某段连续的数字和最大的那一段,输出最大子段的和以及这个字段的起始和结束位置
    用贪心算法,第一个数时最大的数是第一个数,第二个数时与第一个数想加,得到的数与第二个数比较,如果最大的是第二个数,从第二个数开始,反之继续相加
    代码:
    #include<iostream>
    #define N 100010
    using namespace std;
    int a[N],d[N];
    int main()
    {
        int test,n,i,max,k,f,e;
        cin>>test;
        k=1;
        while(test--)
        {
            cin>>n;
            for(i=1;i<=n;i++)
                cin>>a[i];
            d[1]=a[1];
            for(i=2;i<=n;i++)
            {
                if(d[i-1]<0) d[i]=a[i];
                else d[i]=d[i-1]+a[i];
            }
            max=d[1];e=1;
            for(i=2;i<=n;i++)
            {
                if(max<d[i])
                {
                    max=d[i];e=i;
                }
            }
            int t=0;
            f=e;
            for(i=e;i>0;i--)
            {
                t=t+a[i];
                if(t==max)    f=i;
            }
            cout<<"Case "<<k++<<":"<<endl<<max<<" "<<f<<" "<<e<<endl;
            if(test) cout<<endl;
        }
        return 0;
    }
  • 相关阅读:
    Objective-C-使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON字符串
    js showModalDialog打开新的页面给原页面传值问题
    svn2git使用小记
    模拟等待事件row lock waits
    URAL 1994 The Emperor's plan 求组合数 大数用log+exp处理
    struts总结
    URAL 1992 CVS 链表
    android游戏物理引擎开发——粒子系统(三)
    状态模式与上机
    OpenCV——凸包
  • 原文地址:https://www.cnblogs.com/Sikaozhe/p/5481308.html
Copyright © 2020-2023  润新知