动态规划题目,虽然以前学过了算法分析与设计,遇到实际的题目还是不熟悉。
该题目是,求最大字段和,并记录下起始位置。
首先,max:最终的最大字段和
sum:临时字段和,用来与max对比
temp:输入的数据
start:最大字段和的起始位置
end:最大字段和的终点
然后,每输入一个数据
求出 sum+temp 的值,并与temp做对比。如果sum+temp<temp,就记sum=temp,并pos=j;否则就sum+=temp;
将此时的sum与max做对比,如果sum>max则max=sum且start=pos,end=j(j为当前位置);
代码如下:
#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T;
for(int i=1 ; i<=T ; i++)
{
int N , temp , max , sum , start , end , pos ;
cin>>N>>temp;
max = sum = temp;
start = end = pos = 1;
for(int j=2 ; j<=N ; j++)
{
cin>>temp;
if(sum + temp < temp)
{
pos = j;
sum = temp;
}else
sum += temp;
if(max < sum)
{
max = sum;
start = pos;
end = j;
}
}//for
cout<<"Case "<<i<<":"<<endl;
cout<<max<<" "<<start<<" " << end<<endl;
}//for
return 0;
}
转载于:https://blog.51cto.com/shine2014/1551873