HDU - 1003 Max Sum(最大连续子段和)

Max Sum

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的思想。DP数组保存从0~i的最大和,遍历每一个数, 如果加上当前数使得最大和为负数了,那么肯定不能加这个数了,因为要求连续,所以 只能从当前位置开始,重新计算最大和,看看有没有比之前更大的。如

5 6 -10 100,这个时候前三个数的和是1,还是正数,那么肯定可以加上后面的100试试。但如果是 5 6 -12 100,前三个数和为-1,那么即使加上100=99,也没有直接用100大。用两个标记记录区间位置即可。详见代码注释。


#include<iostream>
#include<memory.h>
#include<string>
#include<algorithm>

using namespace std;
const int MAXN=100005;
int dp[MAXN];//保存从0~i的最大和
int a[MAXN];
int N;


int main(){

    int t;
    scanf("%d",&t);

    for(int qqq=0;qqq<t;qqq++){

        scanf("%d",&N);
        for(int i=0;i<N;i++)
            scanf("%d",&a[i]);

        dp[0]=a[0];//初始最大和为第一个数

        int start=0;//开始标记
        int end=0;//结束标记
        int maxsum=dp[0];//最大和
        int tempstart=0;//暂时的开始标记

        for(int i=1;i<N;i++){
            //如果前一个的最大和为正数,证明可以加上现在这个数试试
            if(dp[i-1]>=0){
                dp[i]=dp[i-1]+a[i];
            }
            else{
                dp[i]=a[i];//否则不用加了,直接把最大和变为这个数,因为之前加的那个数使最大和变为了负数,所以不能用那个数,只能重这里开始重新开始计算最大和
                tempstart=i;//相当于从这里开始重新计算最大和,看看从这里开始往后会不会出现更大的和
            }

            //保存最大和
            if(dp[i]>maxsum){
                maxsum=dp[i];
                start=tempstart;//记录开始的地方
                end=i;//结束
            }

        }

        if(qqq!=t-1)
            printf("Case %d:\n%d %d %d\n\n",qqq+1,maxsum,start+1,end+1);
        else
            printf("Case %d:\n%d %d %d\n",qqq+1,maxsum,start+1,end+1);
    }


    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值