hdu4622 后缀自动机 模板

12 篇文章 0 订阅

抄来的代码

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 5050
struct Node
{
    int step;
    Node *pre,*nxt[26];
    void clear()
    {
        step=0;
        pre=NULL;
        memset(nxt,NULL,sizeof(nxt));
    }
    int calc()
    {
        if(pre==NULL) return 0;
        return step-pre->step;
    }
}*root,*last;

Node pool[N*2],*cur;
void init()
{
    cur=pool;
    root=last=cur++;
    root->clear();
}
int tot;
void extend(int w)
{
    Node *np=cur++,*p=last;
    np->clear();
    np->step=p->step+1;
    while(p&&!p->nxt[w])
        p->nxt[w]=np,p=p->pre;
    if(p==NULL)
    {
        np->pre=root;
        tot+=np->calc();
    }
    else
    {
        Node *q=p->nxt[w];
        if(q->step==p->step+1)
        {
            np->pre=q;
            tot+=np->calc(); // q点的值已经算过
        }
        else // q->step!=p->step+1,构造出一个等于p->step+1的
        {
            Node *nq=cur++;
            tot-=p->calc()+q->calc();
            memcpy(nq->nxt,q->nxt,sizeof(q->nxt));
            nq->pre=q->pre;
            nq->step=p->step+1;
            np->pre=q->pre=nq;
            tot+=p->calc()+q->calc()+np->calc()+nq->calc();
            while(p&&p->nxt[w]==q)
                p->nxt[w]=nq,p=p->pre;
        }
    }
    last=np;
}
char str[N];
int ans[N][N];
int main ()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        int n=strlen(str);
        for(int i=0;i<n;++i)
        {
            init();
            tot=0;
            for(int j=i;j<n;++j)
            {
                extend(str[j]-'a');
                ans[i][j]=tot;
            }
        }
        int Q,l,r;scanf("%d",&Q);
        while(Q--)
        {
            scanf("%d%d",&l,&r);
            l--,r--;
            printf("%d\n",ans[l][r]);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值