HDU

来源:互联网 发布:vb中default是什么意思 编辑:程序博客网 时间:2024/06/14 06:34

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
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入门题。但觉得这道题更像是贪心,贪心的选取和最大的部分,稍微思考就可以写出来了,不过用到了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;}





原创粉丝点击