2026/7/18下午 总结

· · 个人记录

P1439 两个排列的最长公共子序列

题面

数状数组+桶数组

本题求两个排列的最长公共子序列(LCS),若用常规 DP 是 O(n²),会超时。

将 LCS 转为 LIS(最长上升子序列)。

树状数组优化 LIS

时间 O(n log n),空间 O(n)。

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+50;
int n,ans,b[N],c[N];
map<int,int>t;
int lowbit(int x){
    return (x&(-x));
}
int query(int x){
    int ans=0;
    while(x>0){
        ans=max(ans,c[x]);
        x-=lowbit(x);
    }
    return ans;
}
void modify(int x,int v){
    while(x<=n){
        c[x]=max(c[x],v);
        x+=lowbit(x);
    }
    return ;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        t[x]=i;
    }
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        b[i]=t[x];
    }
    for(int i=1,c;i<=n;i++){
        c=1;
        c=max(c,query(b[i]-1)+1);
        modify(b[i],c);
        ans=max(ans,c);
    }
    cout<<ans;
    return 0;
}

P1972 [SDOI2009] HH 的项链

题面

关键结论:对于右端点相同的询问,重复数字只需关心最右边那一个的位置。

P9883 [EC Final 2021] Fenwick Tree

题面

分类讨论

  1. 目标为 0:

    • cnt[i] == 0:无需操作。

    • cnt[i] == 1:需要执行一次 update(i, val) 将其抵消为 0,答案 +1。

    • cnt[i] >= 2:可通过构造正负值相互抵消,无需额外操作。

  2. 目标为 1(非零):

    • cnt[i] == 0:需要执行一次 update(i, val) 使其变为非零,答案 +1。

    • cnt[i] >= 1:已有操作使其非零,无需操作。

若在 i 处执行,它会影响下一个位置 i + lowbit(i),因此 cnt[i + lowbit(i)]++。

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+50;
int t,n,ans,cnt[N];
int lowbit(int x){
    return (x&(-x));
}
string s;
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>t;
    while(t--){
        cin>>n>>s;
        for(int i=1;i<=n;i++){
            cnt[i]=0;
        }
        s="#"+s;
        ans=0;
        for(int i=1;i<=n;i++){
            if(s[i]=='1'){
                if(!cnt[i])ans++;
                if(i+lowbit(i)<=n){
                    cnt[i+lowbit(i)]++;
                }
            }else if(cnt[i]==1){
                ans++;
            }
        }
        cout<<ans<<"\n";
    }
    return 0;
}