4516: [Sdoi2016]生成魔咒

本文介绍了一种使用后缀自动机(SAM)解决字符串问题的方法,并通过一个具体的编程实例展示了如何利用SAM算法来计算随着字符串逐步增长过程中不同子串的数量变化。采用map解决了字符集大小的问题,提高了算法的通用性。

题目链接

题目大意:依次向字符串末尾加上一个字符,每次求不同子串个数

题解:SAM模板题,上map就不怕字符集问题了
SA也可以做,不过麻烦一些

注意SAM点数2n

我的收获:SAM+map解决字符集大小问题

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;

const int N=200005;

int n,tot=1,root=1,last=1;
int fail[N],step[N];
long long ans;

map<int,int> ch[N]; 

int calc(int x){return step[x]-step[fail[x]];}

void add(int c){
    int np=++tot,p=last;last=np;
    step[np]=step[p]+1;
    for(;p&&!ch[p][c];p=fail[p]) ch[p][c]=np;
    if(!p) fail[np]=root; else{
        int q=ch[p][c];
        if(step[p]+1==step[q]) fail[np]=q; else{
            int nq=++tot;step[nq]=step[p]+1;ch[nq]=ch[q];
            fail[nq]=fail[q];fail[np]=fail[q]=nq;
            for(;ch[p][c]==q;p=fail[p]) ch[p][c]=nq;
        }
    }
    ans+=calc(np);
}

void init()
{
    scanf("%d",&n);  
    for(int x,i=1;i<=n;i++)  
    {
        scanf("%d",&x);  
        add(x);  
        printf("%lld\n",ans);  
    } 
}

int main()
{
    init();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值