hdu 1003 Max Sum

来源:互联网 发布:制作头像软件 编辑:程序博客网 时间:2024/06/08 01:38

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[i]=max{dp[i-1]+a[i], a[i]}

代码实现

#include<iostream>#include<cstdio>using namespace std;#define MAXN 100010int num[MAXN];int main(){    int T;    int _case;        _case=1;    scanf("%d",&T);    while(T--)    {        int n;        scanf("%d",&n);        for(int i=0;i<n;i++)            scanf("%d",&num[i]);        int sum,_sum;        int _begin,_end,pos;        sum=_sum=num[0];//初始化为num[0],不能初始化为0        _begin=_end=pos=0;//用作标记        for(int i=1;i<n;++i){            sum+=num[i];            if(sum<num[i]){                sum=num[i];                pos=i;            }            if(sum>_sum){                _sum=sum;                _begin=pos;                _end=i;            }        }            printf("Case %d:\n%d %d %d\n",_case++,_sum,_begin+1,_end+1);            if (T)                printf("\n"); //输出格式,最后一个case不能再输出换行符    }    return 0;}
0 0
原创粉丝点击