hdu5558 后缀自动机模板题

题目大意,有一个字符串,有一个指针i,一开始等于0,每次找i前面的j,使从i开始的字符串和从j开始的字符串拥有最长公共前缀,如果没有,输出-1和s[i]的ASCII码值,否则,输出j和长度,然后i+=这个长度

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 100000 + 10;
const int CHAR = 28;
struct SAM_Node
{
    SAM_Node *fa,*next[CHAR];
    int len;
    int id,pos;
    SAM_Node(){}
    SAM_Node(int l)
    {
        fa=0;
        len=l;
        memset(next,0,sizeof(next));
    }
} ;
SAM_Node SAM_node[maxn*2],*SAM_rot,*SAM_last;
int SAM_size;
SAM_Node *newSAM_Node(int len)
{
    SAM_node[SAM_size]=SAM_Node(len);
    SAM_node[SAM_size].id=SAM_size;
    return &SAM_node[SAM_size++];
}
SAM_Node *newSAM_Node(SAM_Node *p)
{
    SAM_node[SAM_size]=*p;
    SAM_node[SAM_size].id=SAM_size;
    return &SAM_node[SAM_size++];
}
void SAM_init()
{
    SAM_size=0;
    SAM_rot=SAM_last=newSAM_Node(0);
    SAM_node[0].pos=0;
}
void SAM_add(int x,int len)
{
    SAM_Node *p=SAM_last,*np=newSAM_Node(p->len+1);
    np->pos=len;
    SAM_last=np;
    for(;p&&!p->next[x];p=p->fa)
    {
        p->next[x]=np;
    }
    if(!p)
    {
        np->fa=SAM_rot;
        return ;
    }
    SAM_Node *q = p->next[x];
    if(q->len==p->len+1)
    {
        np->fa=q;
        return ;
    }
    SAM_Node *nq=newSAM_Node(q);
    nq->len=p->len+1;
    q->fa=nq;
    np->fa=nq;
    for(;p&&p->next[x]==q;p=p->fa)
    {
        p->next[x]=nq;
    }
}
char s[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    for(int kase=1;kase<=T;kase++)
    {
        scanf("%s",s);
        int len=strlen(s);
        printf("Case #%d:\n",kase);
        int now = 0;
        SAM_init();
        while(now<len)
        {
            int num = 0;
            SAM_Node *p = SAM_rot;
            while(now<len&&p->next[s[now]-'a'])
            {
                SAM_add(s[now]-'a',now+1);
                p=p->next[s[now]-'a'];
                num++;
                now++;
            }
            if(num==0)
            {
                printf("-1 %d\n",(int)s[now]);
                SAM_add(s[now]-'a',now+1);
                now++;
            }
            else{
                printf("%d %d\n",num,p->pos-num);
            }
        }
    }
    return 0;
}

你可能感兴趣的:(字符串)