洛谷 P1439 最长公共子序列 LCS转换为LIS

https://www.luogu.org/problem/P1439
题目描述
给出1-n的两个排列P1和P2,求它们的最长公共子序列。
输入格式
第一行是一个数n,
接下来两行,每行为n个数,为自然数1-n的一个排列。
输出格式
一个数,即最长公共子序列的长度

思路: n n n最多可达 1 e 5 1e5 1e5 L C S LCS LCS解法是 O ( n 2 ) O(n^2) O(n2)的,会超时,然而 L C S LCS LCS问题在满足给定的序列中没有重复元素这一条件时是可以转换为 L I S LIS LIS问题的。设给定的两个序列分别为 a a a b b b,对序列 a a a做哈希: h a s h [ a 1 ] = 1 , … … , h a s h [ a i ] = i , … … , h a s h [ a n ] = n hash[a_{1}]=1,……,hash[a_{i}]=i,……,hash[a_{n}]=n hash[a1]=1hash[ai]=ihash[an]=n,由此我们可以得到一个新的序列 c c c,序列 c c c定义为: c i = h a s h [ b i ] c_{i}=hash[b_{i}] ci=hash[bi],序列 c c c L I S LIS LIS的长度即为答案。

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pr pair<int,int>
using namespace std;
typedef long long ll;

const int maxn=1e5+5;

int a[maxn],b[maxn],id[maxn],c[maxn];
int n,len;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]),id[a[i]]=i;
    for(int i=1;i<=n;i++)
        scanf("%d",&b[i]);
    len=0;
    for(int i=1;i<=n;i++)
    {
        if(!len||id[b[i]]>c[len])
            c[++len]=id[b[i]];
        else
            *lower_bound(c+1,c+1+len,id[b[i]])=id[b[i]];
    }
    printf("%d\n",len);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值