1. 程式人生 > 其它 >最長公共子序列(樹狀陣列)

最長公共子序列(樹狀陣列)

只能處理兩個 \(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;
}
$$A\ drop\ of\ tear\ blurs\ memories\ of\ the\ past.$$