HDU_1003 Max Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cherish0222/article/details/69788022

Given a sequence a11,a22,a33......ann, 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. 
InputThe 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). 
OutputFor 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,以前也写过,现在却连续wa了三发,不得不吐槽自己的粗心大意加渣==,ans的初始化应该要赋一个超级小的值啊,不然一定wa


参考代码:

#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<cstring>
#include<string>
#include<sstream>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<iostream>

using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+10;
int n;
int num[maxn];
int sum[maxn];

int main()
{
    int T;
    scanf("%d",&T);
    int cnt = 1;
    while( T--)
    {
        if( cnt > 1)
            putchar(10);
        scanf("%d",&n);
        for( int i = 1; i <= n; i++)
            scanf("%d",&num[i]);
        memset(sum,0,sizeof(sum));

        int ans = -INF;
        int l = 1, r = 1;
        int tmp = 1;
        for( int i = 1; i <= n; i++)
        {

            if( sum[i-1] >= 0)
                sum[i] = sum[i-1]+num[i];
            else
            {
                sum[i] = num[i];
                tmp = i;
            }
            //printf("%d %d\n",sum[i],ans);
            if( sum[i] > ans)
            {
                ans = sum[i];
                l = tmp;
                r = i;
            }
            //printf("%d %d\n",i,sum[i]);
        }
        printf("Case %d:\n",cnt++);
        printf("%d %d %d\n",ans,l,r);


    }

    return 0;
}
展开阅读全文

没有更多推荐了,返回首页