动态规划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;
}
原文地址:https://www.cnblogs.com/Sikaozhe/p/5481308.html