HDU-1003 Max Sum(dp)

Max Sum

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


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
We have carefully selected several similar problems for you:   1176  1087  2084  1159  1203 
 

              大体意思就是让你找到和最大的子串~~这样的话我们来用sum来表示前n项数的和是多少~~如果sum加完后小于0,那么就代表着,这前n项和对后续的影响是负担~做负功的感觉差不多~~所以我们直接舍去这前n项~~重下一项开始计就好了;相反的~加入这时sum>0就代表着前n项的加到后面对于到时候的前几项和是有利的(提升)继续保留就好。

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    int te;
    cin>>te;
    int Ca=1;
    while(te--)
    {
        int n;
        cin>>n;
        int sum=0;
        int maxn=-9999999;
        int mst=1,men=1,st=1;
        for(int s=1;s<=n;s++)
        {
            int a;
            scanf("%d",&a);
            sum+=a;
            if(sum>maxn)
            {
                maxn=sum;
                mst=st;
                men=s;
            }
            if(sum<0)
            {
                sum=0;
                st=s+1;
            }
        }
        printf("Case %d:\n",Ca++);
        printf("%d %d %d\n",maxn,mst,men);
        if(te>=1)
        {
            cout<<"\n";
        }
    }
    return 0;
}












全部评论

相关推荐

小红书 后端选手 n*16*1.18+签字费期权
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
找不到工作死了算了:没事的,雨英,hr肯主动告知结果已经超越大部分hr了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务