HDU 1003 DP 问题

来源:互联网 发布:sql with cte as 编辑:程序博客网 时间:2024/04/27 07:45

Max Sum

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


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 


题目大意: 给出以一组数现在要求求出 最大子序列数, 并且给出序列的初始位置和终端位置

解题方法:简单DP 主要是找到状态方程  sum[i] = max{ sum[i-1] + a[i], a[i] }  再开始使用  这个的意思是什么呢 如果前面和是大于零的 那么继续加

                    如果不是 那么舍弃前面的 从现在开始计数 现在就是开始位置  之后往下加数  
                    这道题最要注意的就是在加和过程中会产生 最大值 可能最后加上一个 负数,那么整个的最大值就会减小的 因此 要用max 来标记最大

源代码:
  
#include<iostream>using  namespace  std;#define  MAX 100000int main(){    //题目大意:就是求最大子序列数, 并且要求出这个序列的位置    //主要利用状态转移方程 sum[i] = max{sum[i-1] +a[i], a[i]}    int t , i;    cin>>t ;    int m;    int count = 1;    while(t--)    {        int n;        cin>>n;        int s ,e;        int a, b;        int sum = -1001;        int max = -1001;        for(int i = 1; i <=n; i++)        {            cin>>m;            if(sum + m < m)            {//根据状态方程                sum = m ;                s = i;                e = i;            }            else            {//这个步骤往下加了一个数                sum += m;                e++;            }            //下面进行动态调试            if(max < sum)            {//为什么要这步 因为之间可能会产生最大值                max = sum ;                a = s;                b = e;            }        }        cout<<"Case "<<count<<":"<<endl;        cout<<max<<" "<<a<<" "<<b<<endl;        count++;    }    return 0;}

0 0
原创粉丝点击