最大递增子序列问题

[题目]

设序列 L=<a1,a2,a3,,an> 是长度为n的序列, L 的一个递增序列描述为:<ai1,ai2,,aik>, 其中下标序列 <i1,i2,,ik> <script id="MathJax-Element-4" type="math/tex">< i_1, i_2, \cdots, i_k></script>是递增的, 子序列 <ai1,ai2,,aik> <script id="MathJax-Element-5" type="math/tex">< a_{i1}, a_{i2}, \cdots, a_{ik}></script> 也是递增的,求此递增序列的长度为 k。

[分析]

常用的动态规划思想算法复杂度为 O(n2) ,改进后的采用二分查找的算法复杂度为 O(nlogn) 。具体分析过程参见下面的博客,讲解的很详细,易懂:最大递增子序列问题

我实现的核心代码如下:

#include <iostream>
using namespace std;
int main(){
    int a[10] = {1,3,4,2,7,5,9,6,8,10};     //待测试数组
    int len=0,t[10];        //t[递增子序列长度]=结尾处的最小值
    t[1]=a[0];      //初始化
    len=1;          //记录当前的最大递增子序列长度
    int l,p,r;      //二分法的下界、中点、上界
    for(int i=1; i<10; i++){
        l=1;
        r=len;
        while(l<=r){    //二分查找
            p=(l+r)/2;
            if(t[p]<a[i])
                l=p+1;
            else
                r=p-1;
        }
        t[l]=a[i];
        if(l>len)
            len++;
    }
    cout<<len<<endl;
    return 0;
}

杭电oj(1025)-Constructing Roads In JGShining’s Kingdom应用的代码如下:

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

#define MAX 500010

typedef struct roads{
    int pool;
    int rich;
};

roads rd[MAX];
int t[MAX];

bool cmp(roads a, roads b){
    if(a.pool < b.pool)
        return true;
    return false;
}

int main(){
    int N,num=1;
    freopen("input","r",stdin);
    while(scanf("%d",&N)!=EOF){
        for(int i=0; i<N; i++)
            scanf("%d%d",&rd[i].pool,&rd[i].rich);   //注意这里要用scanf,使用cin会超时
        sort(rd,rd+N,cmp);
        t[1]=rd[0].rich;
        int len=1;
        int l,m,r;
        for(int i=1; i<N; i++){
            l=1;
            r=len;
            while(l<=r){
                m=(l+r)/2;
                if(t[m] < rd[i].rich)
                    l=m+1;
                else
                    r=m-1;
            }
            t[l]=rd[i].rich;
            if(l>len)
                len++;
        }
        printf("Case %d:\n",num++);
        if(len==1)
            printf("My king, at most %d road can be built.\n\n",len);
        else
            printf("My king, at most %d roads can be built.\n\n",len);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值