跳到正文

题解

一种在 kmp 的同时对所有前缀数 border 的方法

Shunpower约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月30日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 2 分钟
题目
SP21360

版本

  1. v1当前

提供一个可以 O(n)\mathcal O(n) 数出所有前缀 border 数量的方法。感觉还是有用的!


考虑经典结论:border 的 border 是 border。这意味着,当我们用 KMP 算出 s[1:i]s[1:i] 的最长 border s[1:j]s[1:j] 的时候,我们可以继承 s[1:j]s[1:j] 的所有 border。

进一步容易发现由于 s[1:j]s[1:j] 是最长的,所以我们恰好会增多一个 border。于是可以 O(1)\mathcal O(1) 转移。

特别地,需要注意 s[1:i]s[1:i] 没有 border 的边界情况。

C++
int tc;
string s;
int kmp[N],cnt[N];
int main(){
#ifdef Ltp
    freopen("hack.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    ios::sync_with_stdio(false);
    cin>>tc;
    fr1(i,1,tc){
        cout<<"Case "<<i<<": ";
        cin>>s;
        s='@'+s;
        int n=s.length()-1;
        int poi=0;
        fr1(i,2,n){
            while(poi&&s[poi+1]!=s[i]) poi=kmp[poi];
            if(s[poi+1]==s[i]) poi++;
            kmp[i]=poi;
            if(!poi) cnt[i]=0;
            else cnt[i]=cnt[poi]+1;
        }
        cout<<cnt[n]<<'\n';
    }
    ET;
}
//ALL FOR Zhang Junhao.
原文