Problem Description
Given a sequencea[1],a[2],a[3]......a[n], your job is to calculate the max sum of asub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is6 + (-1) + 5 + 4 = 14.
Input
The first line ofthe input contains an integer T(1<=T<=20) which means the number of testcases. Then T lines follow, each line starts with a numberN(1<=N<=100000), then N integers followed(all the integers are between-1000 and 1000)。
Output
For each testcase, you should output two lines. The first line is "Case #:", #means the number of the test case. The second line contains three integers, theMax Sum in the sequence, the start position of the sub-sequence, the endposition of the sub-sequence. If there are more than one result, output thefirst 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
这道题目运用了动态规划的思想,刚开始解题的时候用了3重循环,果断超时。
后来看了正确的解法,确实很巧妙。自己敲了几遍,大概明白了其中的意思。
int main()
{
int T;
cin>>T;
int MAX=0,n,temp,now,subscript1,subscript2,i,x;
int cnt=0;
while(T--)
{
cin>>n>>temp;//输入每组数据个数n和第一个数
now=temp;//对应的变量进行初始化
MAX=temp;
subscript1=1;
subscript2=1;
x=1;
for(i=2;i<=n;i++)
{
cin>>temp;
if(now+temp<temp)//条件满足后,相当于开辟了一个新的子串继续运算
{
now=temp;//now记录着符合要求子串最左端的数字
x=i;//x记录子串最左端数字的下标
}
else
now+=temp;//只要满足now+temp<temp,就把当前读入的数据增加到now中,注意now可能经过此次操作会变小,但是没有关系
if(now>MAX)//这一条件使MAX保存的始终是最大值,决定是不是要改变子串的位置
{
MAX=now;
subscript1=x;
subscript2=i;
}
}
cnt++;
cout<<"Case "<<cnt<<":"<<endl<<MAX<<" "<<subscript1<<" "<<subscript2<<endl<<endl;
}
return 0;
}
算法的第一个if else 语句的作用是找,找出可能连续和最大的子串,一旦now+temp<temp,就是说你输入的这个数不在满足连续子串和最大了,就开始查找新的子串。
第二个if 判断就是从你找出的子串中找出最大的,并记录位置。