洛谷 P1439 【模板】最长公共子序列

洛谷 P1439 【模板】最长公共子序列

Description

  • 给出1-n的两个排列P1和P2,求它们的最长公共子序列。

Input

  • 第一行是一个数n,

    接下来两行,每行为n个数,为自然数1-n的一个排列。

Output

  • 一个数,即最长公共子序列的长度

Sample Input

5
3 2 1 4 5
1 2 3 4 5

Sample Output

3

Data Size

  • 对于50%的数据,n≤1000

    对于100%的数据,n≤100000

题解:

  • 转换思想。
  • 观察数据范围,n方做法肯定会炸。但我才刚学过LIS的nlogn做法。那这题是否同样可用nlogn解决呢?
  • 答案是肯定的。
  • 两个序列a和b。把a序列映射成1-n的连续上升序列,b映射后得到了新序列c。答案就是c序列的LIS。因为连续上升序列保证了a是递增的,这时他们的LCS就是他们的最大LIS。
  • LIS可用树状数组维护
#include <iostream>
#include <cstdio>
#include <map>
#define lowbit(x) (x & (-x))
#define maxn 100005
using namespace std;

int n, cnt, ans;
int a[maxn], b[maxn], c[maxn];
map<int, int> mp;

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

int ask(int pos)
{
    int r = 0;
    while(pos >= 1)
    {
        r = max(r, c[pos]);
        pos -= lowbit(pos);
    }
    return r;
}

void update(int pos, int val)
{
    while(pos <= n)
    {
        c[pos] = max(c[pos], val);
        pos += lowbit(pos);
    }
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++) a[i] = read(), mp[a[i]] = i;
    for(int i = 1; i <= n; i++) b[i] = read();
    for(int i = 1; i <= n; i++) b[i] = mp[b[i]];
    for(int i = 1; i <= n; i++)
    {
        int t = ask(b[i] - 1) + 1;
        update(b[i], t);
        ans = max(ans, t);
    }
    cout << ans;
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11216238.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值