HDU 1003:Max Sum(DP,连续子段和)

                                     Max Sum

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

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

题意

给出一个数组,求连续子段和的最大值

思路

第一次写用的前缀和,写完后发现复杂度太高了,交上去果断TLE

翻了一下以前写的51Nod的一道连续字段和的题,写了出来。复杂度O(n)

首先定义一个变量sum,使sum的值足够小,然后开始输入元素x,如果sum<0(即sum+x<x),将sum的值变为x,起点变为当前x的位置(相当于舍弃了前面的sum的值,从x开始重新累加)。然后定义ans,first,end分别记录最终的最大值,起点,终点。sum每改变一次,让ans和sum进行比较,如果ans<sum,更新ans的值,并将起点first为l,终点end变为当前x的位置i,最后输出即可。

一篇关于最大连续子序列和的讲的很不错的博客:https://blog.csdn.net/samjustin1/article/details/52043369。里面还有好多种写法,很详细

AC代码

#include<bits/stdc++.h>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
using namespace std;
const int maxn=1e6+10;
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    int _=0;
    while(t--)
    {
        int n;
        cin>>n;
        int m;
        ll ans=INT_MIN;
        ll sum=INT_MIN;
        int l;
        // sum,sum为临时记录最大值和起点位置的变量
        int first,end;
        for(int i=1;i<=n;i++)
        {
            cin>>m;
            //如果sum小于0,让sum从m重新开始
            //并改变l的值
            if(sum+m<m)
            {
                sum=m;
                l=i;
            }
            else
                sum+=m;
            // 如果ans小于sum,更新ans,first,end
            if(ans<sum)
            {
                first=l;
                end=i;
                ans=sum;
            }
        }
        cout<<"Case "<<++_<<':'<<endl;
        cout<<ans<<" "<<first<<" "<<end<<endl;
        // 注意输出。最后一组样例中没有空行,前面每组之间都有空行
        if(t)
            cout<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Friends-A/p/10324420.html