Max Sum

来源:互联网 发布:360wifi网络不稳定 编辑:程序博客网 时间:2024/05/18 03:42

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
这题是经典的动态规划,还不是很难。题目大概是是说给你一串数字,你选择两个数字,把它们之间所有的数相加,使得到的和最大,输出最大值以及开始的加的数以及结束的数。
比如第一组6 -1 5 4 -7,从第一个6加到第四个4,6+(-1)+5+4+(-7)=14。
可以从第一个开始每个位置能得到的最大的和依次算出来。除了第一个位置,其他位置都能选择的加上或者不加前一个数的最大和来得到自己的最大和。同时我用m标记最大的位置。
#include<cstdio>#include<algorithm>#define size 100009using namespace std;int a[size];int main(){int t,i,n,g=1;scanf("%d",&t);while(t--){int flag=0;scanf("%d",&n);for(i=1;i<=n;i++)scanf("%d",&a[i]);int sum=0,s=1,b=1,e=1,max=a[1];for(i=1;i<=n;i++){sum+=a[i];if(sum>max){max=sum;s=b;e=i;}if(sum<0){sum=0;b=i+1;}}printf("Case %d:\n",g++);printf("%d %d %d\n",max,s,e);if(t!=0)printf("\n");}return 0;}

0 0