Max Sum (dp)
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題)
Max Sum (dp)