HDU 1003 经典DP

Max Sum

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


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




此题是经典的DP,求最大子序列和,转移方程为:dp[i-1]+a[i]>a[i]?dp[i]=dp[i-1]+a[i]:a[i];   然后ans=max{dp[i]};

dp[i]表示的是以i结尾的所有子序列和的最大值,比如第一个样例:5个数 6 -1 5 4 -7 求得的dp[i]为 6 5 10 14 7  表明以i=3结尾的所有子序列[6 -1 5],[6 -1],[-1 5],[6]和的最大值为10,其他的也都是这样。终止位置为求得最大值的下标i,起始位置就从结尾位置开始往回扫并求和,等于最大值的时候就是起始位置。

AC代码:

#include
#include
#include
#include
#include
using namespace std;
int a[100010],dp[100010];


int main()
{
    int t,n,k=1,st,ed;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            a[i]=0;
            scanf("%d",&a[i]);
        }
        dp[1]=a[1],st=1,ed=1;
        int maxn=dp[1];
        for(int i=2;i<=n;i++){
            if(dp[i-1]+a[i]>a[i])dp[i]=dp[i-1]+a[i];
            else dp[i]=a[i];
            if(dp[i]>maxn){
                maxn=dp[i];
                ed=i;
            };
        }
        int sum=0;
        for(int i=ed;i>0;i--){
            sum+=a[i];
            if(sum==maxn)st=i;
        }
        printf("Case %d:\n%d %d %d\n",k++,maxn,st,ed);
        if(t)printf("\n");
    }
    return 0;
}


你可能感兴趣的:(HDU 1003 经典DP)