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
3 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -513 1 2 3 -100 1 2 3 -100 1 2 1 1 1
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6Case 3:6 1 3这个题要注意一句:如果有相等的,输出最靠前的一个这个是正确的代码:#include <stdio.h> #include <iostream> using namespace std; int a[100005]; int main() { int t; cin >> t; for(int j=1;j<=t;j++) { int n; cin >> n; for(int i=0;i<n;i++) { cin >> a[i]; } int x=0;//必须初始化,防止全是负数的数据 int y=0; int start=0; int end=0; int max=a[0]; int sum=a[0]; for(int i=1;i<n;i++) { if(sum<0) { sum=a[i]; x=y=i; } else { sum+=a[i]; y++; } if(sum>max) { max=sum; start=x; end=y; } } cout << "Case "<<j<<":\n"; if(j==t) cout << max<<" "<<start+1 << " "<< end+1 <<endl; else cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl; } return 0; }
如果没有这句话,代码可以写为:#include <stdio.h> #include <iostream> using namespace std; int a[100005]; int main() { int t; cin >> t; for(int j=1;j<=t;j++) { int n; cin >> n; for(int i=0;i<n;i++) { cin >> a[i]; } int start=0; int end=0; int max=a[0]; int sum=a[0]; for(int i=1;i<n;i++) { if(sum<0) { start=i; sum=0; } sum+=a[i]; if(sum>=max) { max=sum; end=i; // cout << end << endl; } } cout << "Case"<<" "<<j<<":\n"; if(j==t) cout << max<<" "<<start+1 << " "<< end+1 <<endl; else cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl; } return 0; }
版权声明:本文为u013573047原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。