poj1509 Glass Beads,后缀自动机

来源:互联网 发布:php转换特殊字符 编辑:程序博客网 时间:2024/06/06 00:16
后缀自动机是愈发流行的字符串工具。
两年前我就学习了这个玩意,但是,现在拿起来还是那么陌生。
要完全理解并应用似乎是很难的过程。

poj1509 Glass Beads
每次找最小的字母边转移,转移l次,找到的就是最小串表示的结尾点。

为什么每次找最小的子字母边转移,不会使得在没找到l次后就到达结束状态(没法再转移下去了)呢?
因为,后缀自动机可以串接受所有后缀。如果一个后缀长度小于l,由于开始倍增过,这个后缀一定存在某个长度大于l的后缀使得那个后缀的前缀和这个后缀是一样的,当前状态将能够识别那个后缀,继续转移下去。
好绕口,举例来说,对于l+i这个位置的后缀,i这个位置的后缀的前缀和l+i位置的后缀是一样的,当前状态如果是识别了l+i,那么也一定还能继续识别i。

其实这个过程就是一个筛选后缀的过程。假设有一个集合。起先,集合中包含了所有的后缀,每次找最小的边转移,就是找出后缀中当前字符最小的。

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define Maxn 10100int root,last;//samint tots;struct sam_node{    int fa,son[26];    int len;    void init(int _len){len=_len;fa=-1;memset(son,-1,sizeof(son));}}t[Maxn*2];//length*2void sam_init(){    tots=0;    root=last=0;    t[tots].init(0);}void extend(char ch){    int w=ch-'a';    int p=last;    int np=++tots;t[tots].init(t[p].len+1);    int q,nq;    while(p!=-1&&t[p].son[w]==-1){t[p].son[w]=np;p=t[p].fa;}    if (p==-1) t[np].fa=root;    else{        q=t[p].son[w];        if (t[p].len+1==t[q].len){t[np].fa=q;}        else{            nq=++tots;t[nq].init(0);            t[nq]=t[q];            t[nq].len=t[p].len+1;            t[q].fa=nq;t[np].fa=nq;            while(p!=-1&&t[p].son[w]==q){t[p].son[w]=nq;p=t[p].fa;}        }    }    last=np;}char s[Maxn];int main(){    int cas,l,i,j,now;    scanf("%d",&cas);    while(cas--){        scanf("%s",s);        l=strlen(s);        sam_init();        for(i=0;i<l;++i) extend(s[i]);        for(i=0;i<l;++i) extend(s[i]);        now=root;        for(i=1;i<=l;++i){            for(j=0;j<26;++j){                if (t[now].son[j]!=-1) {now=t[now].son[j];break;}            }        }        printf("%d\n",t[now].len-l+1);    }    return 0;}


0 0
原创粉丝点击