最优子序列求和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/archive/2010/10/10/1847104.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值