uva10635(LCS转换为求LIS)

本文介绍了一种利用最长递增子序列(LIS)求解最长公共子序列(LCS)问题的方法,通过重新编号和使用lower_bound算法将复杂度从O(n*n)降低到O(n*logn)。

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

链接:点击打开链接

题意:求两个串的最长公共子序列(两个串长度最大为250*250)

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
int a[100005],b[100005],dp[100005],pos[100005];
int main(){                                     //样例A={1,7,5,4,8,3,9},B={1,4,3,5,6,2,8,9}
    int t,n,p,q,i,j,cas;                        //因为A,B中,每个数字只出现一次,因此对A,B中的
    scanf("%d",&t);                             //数进行重新编号,编号后
    for(cas=1;cas<=t;cas++){                    //A={0,1,2,3,4,5,6},B={0,3,5,2,-1,-1,4,6}
        scanf("%d%d%d",&n,&p,&q);               //-1代表没出现过,因此就变成求数组B的LIS
        memset(dp,INF,sizeof(dp));              //因此就从O(n*n)的LCS转换成O(n*logn)的LIS
        memset(pos,-1,sizeof(pos));
        for(i=0;i<p+1;i++){
            scanf("%d",&a[i]);
            pos[a[i]]=i;
        }
        for(i=0;i<q+1;i++){
            scanf("%d",&b[i]);
            b[i]=pos[b[i]];
        }
        for(i=0;i<q+1;i++)
        *lower_bound(dp,dp+q+1,b[i])=b[i];
        printf("Case %d: %d\n",cas,lower_bound(dp,dp+q+1,INF)-dp);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值