树状数组来处理 LIS 问题

· · 算法·理论

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

这道题是求解 LIS 的,我们都知道经典的 O(n \log n) 求解 LIS 需要写一个很烦的二分,但是树状数组就不用啦。

观察动态规划转移方程:

f_i=\max_{a_j\leq a_i} f_j +1

注意到这就是一个二维偏序问题,所以树状数组轻松解决,对于我这种数据结构爱好者简直是福音。

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const LL N=1e5+5;
LL n,a[N],b[N],t[N],f[N],mx;
map<LL,LL>m;
LL lowbit(LL x)
{
    return x&-x;
}
LL query(LL x)
{
    LL ans=0;
    while(x)
    {
        ans=max(ans,t[x]);
        x-=lowbit(x);
    }
    return ans;
}
void update(LL x,LL y)
{
    while(x<=n)
    {
        t[x]=max(t[x],y);
        x+=lowbit(x);
    }
}
int main()
{
    scanf("%lld",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
        m[a[i]]=i;
    }
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&b[i]);
        b[i]=m[b[i]];
    }
    for(int i=1;i<=n;i++)
    {
        f[i]=query(b[i])+1;
        update(b[i],f[i]); 
        mx=max(f[i],mx);
    }
    printf("%lld",mx);
}