zoukankan      html  css  js  c++  java
  • 最优子序列求和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算法的问题还有很多,我会在以后的学习当中逐步加以补充的)

  • 相关阅读:
    记一次DRF问题排障
    贷款
    wpf 手指触摸图片放大缩小 设置放大缩小值
    wpf下的图片放大缩小
    WPF 鼠标移动到图片变大,移开还原,单击触发事件效果
    导出压缩
    Sql Server 数据库分页存储过程书写
    Asp.Net Core MVC传值 Asp.Net Core API 前台写法
    MVC下拉框
    Dapper和EF学习
  • 原文地址:https://www.cnblogs.com/FCWORLD/p/1847104.html
Copyright © 2011-2022 走看看