最优子序列求和DP算法(效率较高)

 

        首次接触了一些有关dp算法的题型,开始还有点思路,但在编程的过程当中遇到了些障碍,经过一番辛苦搜索,最后,总算是把最优子序列的算法给想明白了。

int maxSubSum4( const vector<int> & a )

{

int maxSum = 0, thisSum = 0;

for( int j = 0; j < a.size( ); j++ )

{

thisSum += a[ j ];//求一段子序列的和

if( thisSum > maxSum )//验证该段子序列是否是所求的最大和,即最大和非负或者为最大负数

maxSum = thisSum;

else if( thisSum < 0 )

thisSum = 0;//任何负的子序列不可能是最优子序列的前缀 (需要做题慢慢体会)

}

return maxSum;

}

 

hdu1003
1 #include"iostream"
2  using namespace std;
3  int main()
4 {
5 int n,m,a,i,j=0;
6 cin>>n;
7 while(n)
8 {
9 cin>>m;
10 int sum=0,k=0,max=-99999999,start=0,end=0;
11 for(i=0;i<m;i++)
12 {
13 cin>>a;
14 sum+=a;
15 if(sum>max)
16 {
17 max=sum;
18 start=k+1;
19 end=i+1;
20
21 }
22
23 if(sum<0) { sum=0; k=i+1;}
24 }
25
26 cout<<"Case"<<" "<<++j<<":"<<endl;
27 cout<<max<<" "<<start<<" "<<end<<endl;
28 if(n>1) cout<<endl;
29 n--;
30 }
31 return 0;
32 }

(注:涉及到DP算法的问题还有很多,我会在以后的学习当中逐步加以补充的)

原文地址:https://www.cnblogs.com/FCWORLD/p/1847104.html