A - 最大子段和
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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
题解:
求最大子序列和,及其初始和结束位置。 如果有多解,输出最先算出的。
两种方法,一看就懂得了
#include <cstdio> int main() { int T,k, R, L, Max, sum, t, total=1, n; scanf("%d", &T); while(T--) { sum = Max =-100; //足够小就好 scanf("%d", &n); for(int i=1; i<=n; i++) { scanf("%d", &t); if (sum<0) { sum = t, k = i; } else sum += t; if (Max < sum) Max = sum, L = k, R = i; //L R分别为初始和结束位置 } printf("Case %d: ", total++); printf("%d %d %d ", Max, L, R ); if (T) printf(" "); } return 0; }
#include<iostream> using namespace std; int a[100010],b[100010]; int main() { int n,T,s,t,max,total,k=1; cin>>T; while(T--) { cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; b[1]=a[1]; for(int i=2; i<=n; i++) { if(b[i-1]<0) b[i]=a[i]; else b[i]=b[i-1]+a[i]; } max=b[1]; s=1; for(int i=2; i<=n; i++) { if(b[i]>max) { max=b[i]; s=i; } } t=s; total=0; for(int i=s; i>=1; i--) { total+=a[i]; if(total==max) t=i; } cout<<"Case "<<k++<<":"<<endl; cout<<max<<" "<<t<<" "<<s<<endl; if(T) cout<<endl; } }