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

hdu1003 简单DP

时间:2016-05-07 23:43:18      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

Max Sum

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


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]>=0 dp[i]=dp[i-1]+a[i],else dp[i]=a[i]

在起始位置和终点位置的保存上傻了一下,起始只要在状态转移的时候维护begin和

end两个值即可,在max更新的时候同时更新begin和end.要注意的是输出格式,每两个

输出之间要有空行,最后一个case则不需要空行。

代码:

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
const int maxn=100000+100;
int dp[maxn],a[maxn];
int kase=0;
int main()
{
       int T;
       scanf("%d",&T);
       while(T--)
       {
           memset(dp,0,sizeof(dp));
           int n,x;
           scanf("%d",&n);
           for(int i=1;i<=n;i++)
           scanf("%d",&a[i]);
           int b,e;
           int ma;
           x=b=e=1;
           ma=dp[1]=a[1];
            for(int i=2;i<=n;i++)
           {
                  if(dp[i-1]>=0)
                  {
                      dp[i]=dp[i-1]+a[i];
                  }
                  else
                  {
                      dp[i]=a[i];
                      x=i;//临时储存开始位置
                  }
              if(dp[i]>ma)
              {
                  ma=dp[i];
                  b=x;
                  e=i;//更新起始位置和终点位置
              }
           }
           cout<<"Case "<<++kase<<":"<<endl;
           cout<<ma<<" "<<b<<" "<<e<<endl;
           if(T>=1) cout<<endl;
       }
}

hdu1003 简单DP

标签:

原文地址:http://www.cnblogs.com/xuejianye/p/5469373.html

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