HDU4622(后缀自动机)

本文详细介绍了使用后缀自动机解决给定字符串区间内不同子串计数的问题,包括模板代码解析、算法原理及具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Reincarnation


题意:给定一个字符串,然后再给定Q个询问,每个询问是一个区间[l,r],问在这个字符串区间中有多少个不同的子串。


后缀自动机模版题:

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>

using namespace std;
const int N=5010;

struct State
{
    State *pre,*go[26];
    int step;
    void clear()
    {
        pre=0;
        step=0;
        memset(go,0,sizeof(go));
    }
    int calc()
    {
        if(pre==0) return 0;
        return step-pre->step;
    }
}*root,*last;

State statePool[N*2],*cur;

void init()
{
    cur=statePool;
    root=last=cur++;
    root->clear();
}

int tot;
void Insert(int w)
{
    State *p=last;
    State *np=cur++;
    np->clear();
    np->step=p->step+1;
    while(p&&!p->go[w])
        p->go[w]=np,p=p->pre;
    if(p==0)
    {
        np->pre=root;
        tot+=np->calc();
    }
    else
    {
        State *q=p->go[w];
        if(p->step+1==q->step)
        {
            np->pre=q;
            tot+=np->calc();
        }
        else
        {
            State *nq=cur++;
            nq->clear();
            memcpy(nq->go,q->go,sizeof(q->go));
            tot-=p->calc()+q->calc();
            nq->step=p->step+1;
            nq->pre=q->pre;
            q->pre=nq;
            np->pre=nq;
            tot+=p->calc()+q->calc()+np->calc()+nq->calc();
            while(p&&p->go[w]==q)
                p->go[w]=nq, p=p->pre;
        }
    }
    last=np;
}

int ans[N][N];
char s[N];

void work()
{
    scanf("%s",s);
    int n=strlen(s);
    for(int i=0;i<n;++i)
    {
        init();
        tot=0;
        for(int j=i;j<n;++j)
        {
            Insert(s[j]-'a');
            ans[i][j]=tot;
        }
    }
    int nQ;
    scanf("%d", &nQ);
    while (nQ--)
    {
        int l, r;
        scanf("%d%d", &l, &r);
        --l,--r;
        printf("%d\n", ans[l][r]);
    }
}

int main()
{
    int T;
    cin>>T;
    while(T--)
        work();
    return 0;
}


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值