a program

本文介绍了一个用于求解最长递减子序列(LDS)问题的高效算法实现,并通过一个C++程序示例展示了如何计算给定整数数组中最长递减子序列的长度。该算法采用动态规划思想,利用二分查找提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;

int quick_lds( int  n, int a[], int d[] )
{
       int ans = 0;
       for(int i=1; i<=n; ++i)
       {

              int j = 1;
              int k = ans;
              while( j <= k )

              {
                     int m = ( j + k ) >> 1;

                     if( d[m] < a[i] ) j = m + 1;

                     else k = m - 1;
              }     

              if( j > ans ) ++ans;

              d[j] = a[i];

       }
       return ans;   
}

void main()
{
 int n = 0, max_num = 0;
 int i, j;

 cout << "Please input the number of the array element:" << endl;
 cin >> n;

 if (n < 1)
  return ;
 else cout << "Please input "<< n << " integers:"<< endl;

 int * a = new int [n];
 int * record = new int [n];
 
 for (i = 0; i < n; ++i)
 {
  cin >> a[i];
  record[i] = 1;
 }
/*
 for (i = n - 2; i >= 0; --i)
 {
  for (j = i + 1; j < n; ++j)
  {
   if (record[i] < record[j] + 1 && a[i] < a[j])
    record[i] = record[j] + 1;
  }
 }

 for (i = 0; i < n; ++i)
 {
  if (max_num < record[i])
   max_num = record[i];
 }
 
 cout<<"The answer is: "<<max_num<<endl;*/

 cout<<endl<<quick_lds(n,a, record)<<endl;

 delete[] record;
 record = NULL;
 delete[] a;
 a = NULL;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值