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这道题的题意是在一个序列中求一个子序列的和是最大的。算法思想:当和(sum)大于最大和是将此值付给最大值,并修改子序列的开始和结束;如果和(sum)小于0时sum=0;则子序列的开始等于访问数组的当前位置加1。在本程序中利用C++中的引用来传递子序列的开始和结束的位置程序代码:#include <stdio.h> #include <stdlib.h> #include<iostream> using namespace std; int a[100001]; int maxnum(int *data,int n,int &s,int &e) { int temp=-100000000; int sum=0; int i,j; for(i=0,j=0;i<n;i++) { sum=sum+data[i]; if(sum>temp) { temp=sum; s=j; e=i; } if(sum<0) { sum=0; j=i+1; } } return temp; } int main() { int T,N,s,e,i,j; while(scanf("%d",&T)!=EOF) { for(i=0;i<T;i++) { s=0,e=0; scanf("%d",&N); for(j=0;j<N;j++) { scanf("%d",&a[j]); } printf("Case %d:\n",i+1); printf("%d ",maxnum(a,N,s,e)); printf("%d %d\n",s+1,e+1); if(i<T-1) printf("\n"); } } return 0; }