[SPOJ-DISUBSTR]Distinct Substrings

Posted 租酥雨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[SPOJ-DISUBSTR]Distinct Substrings相关的知识,希望对你有一定的参考价值。

vjudge

题意

给你一个串,求不同字串个数。
\(n\le10^5\)

sol

直接建SAM然后输出\(\sum_{i=1}^{tot}len[i]-len[fa[i]]\)

code

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e5+5;
int T,n,last=1,tot=1,tr[N][26],fa[N],len[N];
char s[N];long long ans;
void extend(int c)
{
    int v=last,u=++tot;last=u;
    len[u]=len[v]+1;
    while (v&&!tr[v][c]) tr[v][c]=u,v=fa[v];
    if (!v) fa[u]=1;
    else
    {
        int x=tr[v][c];
        if (len[x]==len[v]+1) fa[u]=x;
        else
        {
            int y=++tot;
            memcpy(tr[y],tr[x],sizeof(tr[y]));
            fa[y]=fa[x];fa[x]=fa[u]=y;len[y]=len[v]+1;
            while (v&&tr[v][c]==x) tr[v][c]=y,v=fa[v];
        }
    }
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        scanf("%s",s+1);n=strlen(s+1);
        ans=0;last=tot=1;
        memset(tr,0,sizeof(tr));
        memset(fa,0,sizeof(fa));
        memset(len,0,sizeof(len));
        for (int i=1;i<=n;++i) extend(s[i]-'A');
        for (int i=1;i<=tot;++i) ans+=len[i]-len[fa[i]];
        printf("%lld\n",ans);
    }
    return 0;
}

以上是关于[SPOJ-DISUBSTR]Distinct Substrings的主要内容,如果未能解决你的问题,请参考以下文章

C - Distinct Substrings (模板)

LeetCode Distinct Subsequences

LeetCode Distinct Subsequences

115. Distinct Subsequences

lc 115. Distinct Subsequences

Distinct Subsequences