Max Sum (dp)

时间:2021-07-09 17:05:36
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=,cnt=;
cin >> t;
while (t--)
{
if (cnt) cout << endl;
cnt = ;
mark++;
int temp = , frist, end;
int n,ko,sum=,max=-;
cin >> n;
for (int i = ; i < n; i++)
{
cin >> ko;
sum += ko;
if (sum > max)
{
max = sum; frist = temp; end = i + ;
}
if (sum < )
{
sum = ; temp = i + ;
}
}
cout << "Case " << mark << ":" <<endl<< max << " " << frist << " " << end << endl;
}
return ;
}

注意:因为要输出下标,必须灵活应用temp这个中间值,刚开始因为一直没仔细考虑下标的情况,导致负数情况下不能出正确答案;

通过temp的加入后,可以在大于max的条件满足下更改最后的下标,小于零的情况下可以更改temp,到累计大于max时,直接改frist;

(经典DP题)