「模板」最长公共子序列(树状数组)

只能处理两个 \(n\) 的排列的最长公共子序列。

映射存相对位置。

#include <bits/stdc++.h>

using namespace std;

template <typename T>
void read(T &x)
{
    x = 0; int f = 1; char c = getchar();
    while(!isdigit(c)) {if(c == '-') f = -1; c = getchar();}
    while(isdigit(c)) x = x * 10 + c - '0', c = getchar();
    x *= f;
}

template <typename T>
void write(T x)
{
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

const int N = 1e5 + 5;
int n, ans, a[N], b[N], pos[N];
int c[N];

void add(int x, int y)
{
    for(; x <= n; x += x & -x)
        c[x] = max(c[x], y);
}

int qry(int x)
{
    int res = 0;
    for(; x; x -= x & -x)
        res = max(res, c[x]);
    return res; 
}

int main()
{
    read(n);
    for(int i = 1; i <= n; i++) read(a[i]);
    for(int i = 1; i <= n; i++) read(b[i]), pos[b[i]] = i;
    for(int i = 1; i <= n; i++)
    {
        int len = qry(pos[a[i]]) + 1;
        add(pos[a[i]], len);
    }
    write(qry(n)), puts("");
    return 0;
}
posted @ 2021-10-22 12:03  Acestar  阅读(50)  评论(0编辑  收藏  举报