动态规划之求最大连续和

最大连续和其实我们需要考虑的就是在i位置上的数字我们到底放不放进去 这样我们就可以得到一个递推公式了:DP[i]=max(dp[i],dp[i-1]+a[i]) 最后还要对DP进行一个排序找最大的连续和

这道题还有一个要求就是让我们找到这个最大连续和在给的序列中寻找起点和终点 我们只需要对起点和中点进行标记即可 好了 现在就是贴上我AC的代码

Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 329419 Accepted Submission(s): 78432

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

#include
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define inf 0x3f3f3f3f
using namespace std;

const int maxn=1e5+50;
LL dp[maxn][2];
LL a[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    int x=0;
    while(T--)
    {
        int n,i;
        scanf("%d",&n);
        for(i=1;i<=n;i++)
            scanf("%lld",&a[i]);
        mem(dp,0);
        LL mamx=-inf;
        int st,ed;
        for(i=1;i<=n;i++)
        {
            if(dp[i-1][1]+a[i]>=a[i])//我们去一个二维数组,如果是连续最大和中的数就放在dp[i][1]中,若不是就放在dp[i][0]当中
                dp[i][1]=dp[i-1][1]+a[i];
            else
            {
                dp[i][1]=a[i];//需要注意的是 因为前面的数不能作为连续最大和 所以前面的数需要作废
                dp[i][0]=a[i];//并且需要把新的最大连续和的书添加进dp[i][1]和dp[i][0]两个当中
            }
            if(dp[i][1]>mamx)
            {
                ed=i;
                mamx=dp[i][1];
            }
            //printf("%lld  ",dp[i][1]);
            //printf("%lld  ",dp[i][0]);
           //printf("%lld\n",mamx);
        }
        for(i=ed;i>=1;i--)
        {
            if(dp[i][0])
            {
                st=i;
                break;
            }
        }
        if(i==0)
            st=1;
        printf("Case %d:\n%lld %d %d\n",++x,mamx,st,ed);
        if(T!=0)
            cout<

你可能感兴趣的:(DP)