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.
InputThe 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).
OutputFor 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<iostream> #include<map> using namespace std; int main() { int t,mark=0,cnt=0; cin >> t; while (t--) { if (cnt) cout << endl; cnt = 1; mark++; int temp = 1, frist, end; int n,ko,sum=0,max=-100000; cin >> n; for (int i = 0; i < n; i++) { cin >> ko; sum += ko; if (sum > max) { max = sum; frist = temp; end = i + 1; } if (sum < 0) { sum = 0; temp = i + 2; } } cout << "Case " << mark << ":" <<endl<< max << " " << frist << " " << end << endl; } return 0; }
注意:因为要输出下标,必须灵活应用temp这个中间值,刚开始因为一直没仔细考虑下标的情况,导致负数情况下不能出正确答案;
通过temp的加入后,可以在大于max的条件满足下更改最后的下标,小于零的情况下可以更改temp,到累计大于max时,直接改frist;
(经典DP题)
原文地址:https://www.cnblogs.com/kangdong/p/8455259.html