码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1003- Max Sum(DP优化入门题目)

时间:2014-08-26 13:43:46      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:hdu1003   dp   动态规划   c++   

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[i]来记录,以a[i]为字串末位的最大字串和。

如果dp[i-1]+a[i]>a[i] 则dp[i]=dp[i-1]+a[i]。否则dp[i]=a[i]实现动态规划。

效率 O(n)

<span style="font-size:24px;">#include <iostream>
#include <cstring>
using namespace std;
int times,n,maxm;
int a[100010],dp[100010],S,T,ts,tt;
void solv(){
    ts=tt=S=T=0;
    for(int i=0;i<n;i++){
        if(i==0){
            dp[0]=a[0];
            maxm=dp[0];
        }
        else{
            if(dp[i-1]>=0){
                dp[i]=dp[i-1]+a[i];
                tt++;
            }
            if(dp[i-1]<0){
                dp[i]=a[i];
                ts=i;
                tt=0;
            }
            if(dp[i]>maxm){
                  maxm=dp[i];
                  S=ts;
                  T=tt;
            }
        }
    }
}
int main(){
    cin>>times;
    for(int i=0;i<times;i++){
        memset(dp,0,sizeof(dp));
        cin>>n;
        for(int j=0;j<n;j++) cin>>a[j];
        solv();
        if(i==0) cout<<"Case "<<i+1<<":\n"<<maxm<<" "<<S+1<<" "<<S+T+1<<endl;
        if(i!=0) cout<<"\nCase "<<i+1<<":\n"<<maxm<<" "<<S+1<<" "<<S+T+1<<endl;
    }
    return 0;
}
</span>



HDU1003- Max Sum(DP优化入门题目)

标签:hdu1003   dp   动态规划   c++   

原文地址:http://blog.csdn.net/enterpine/article/details/38846079

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!