HDU1003 Max Sum(动态规划,最大子序列和)

95 阅读1分钟

题目:

Max Sum

**Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 230422    Accepted Submission(s): 54269
**
\

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
  
  

 

\

Author

Ignatius.L

 

\

Recommend

 

\

Statistic |  Submit |  Discuss |  Note

思路:

题目给了n个数,让你从中截取一段数列,使他的和最大,并且需要最大和的数列的起始和结束位置,思路就是逐渐递推,以第一个样例为准,我们的递推思路是,以当前的为最后一个数,使当前的和最大的数列,则分别为,6,6,10,14,14,所以最大的就是14,在这个问题中,先把最大值初始化为-1001,因为题目的范围最小是它,然后用两个变量记录首尾,用sum逐渐累加当前的和然后用sum和当前最大的进行比较,更新最大值,再更新首尾的位置,因为题目的为置是从1开始的,所以当sum位负值的时候,temp=i+2,其中i+1是当前位置,则i+2表示下一个位置。

代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
int main()
{
    int t;
    scanf("%d",&t);
    for(int q=1;q<=t;q++)
    {
        int a,n;
        scanf("%d",&n);
        int sum=0,maxsum=-1001,first=0,last=0,temp=1;//最大的数初始化为最大值
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a);
            sum+=a;//计算当前的和
            if(sum>maxsum)
            {
                maxsum=sum;//递推最大值
                first=temp;//首项的位置
                last=i+1;//更新尾项
            }
            if(sum<0)
            {
                sum=0;
                temp=i+2;//当最大子序列和小于0时,将temp=i+2其中i+1表示当前位置,i+2就表示当前位置的下一个位置了。既此最大子序列和为负值,那么下一个的最大子序列和应该是它本身,而不再累加前边的。
            }
        }
        printf("Case %d:\n%d %d %d\n",q,maxsum,first,last);
        if(q!=t)printf("\n");
    }
    return 0;
}


\