BZOJ[4327]JSOI2012 玄武密码 AC自动机

33 篇文章 0 订阅
7 篇文章 0 订阅

题目链接

将每个子串插入AC自动机中,用主串上去匹配,每个走过的点x都是主串的一个前缀

因为一个点的Fail一定是它的后缀,这样沿着x的Fail一直向上爬就可以标记出每一个出现的子串(前缀的后缀,就是原串的一个字串),遇见标记过的就停止,这样保证每个点只被走一次

插入子串时,记录每个子串的结束位置,统计时沿着每个字串的结束点一直向上爬,找到第一个被标记的点就是最长的前缀
注意这里的向上爬的意思是向上爬树边,并不是爬Fail,可以在插入的时候维护每个点的父节点,一直爬父亲即可

代码如下:

#include<cstring>
#include<ctype.h>
#include<cstdio>
#include<queue>
using namespace std;
inline int read(){
    int x=0,f=1;char c;
    do c=getchar(),f=c=='-'?-1:f; while(!isdigit(c));
    do x=(x<<3)+(x<<1)+c-'0',c=getchar(); while(isdigit(c));
    return x*f;
}
int trans(char x){
    if(x=='E') return 0;
    if(x=='S') return 1;
    if(x=='W') return 2;
    if(x=='N') return 3;
}
struct Node{
    Node *ch[4],*nex,*pa;
    int dep;
    bool b;
    Node():nex(NULL),pa(NULL),b(false){
        dep=0;///dep表示这个点长度
        for(int i=0;i<4;i++)
            ch[i]=NULL;
    }
}*root=new Node,*tail[100020];///存每个子串的结束点
queue<Node*>q;
int len,m;
char s[10000200],c[105];
void Insert(char *s,int id){
    int len=strlen(s+1);
    Node *x=root;
    for(int i=1;i<=len;i++){
        if(!x->ch[trans(s[i])])  x->ch[trans(s[i])]=new Node,x->ch[trans(s[i])]->pa=x;
        x->ch[trans(s[i])]->dep=x->dep+1;
        x=x->ch[trans(s[i])];
    }
    tail[id]=x;
}
inline void GetFail(){
    for(int i=0;i<4;i++){
        if(root->ch[i]) q.push(root->ch[i]),root->ch[i]->nex=root;
        else root->ch[i]=root;
    }
    while(!q.empty()){
        Node *x=q.front();q.pop();
        for(int i=0;i<4;i++){
            if(x->ch[i]) x->ch[i]->nex=x->nex->ch[i],q.push(x->ch[i]);
            else x->ch[i]=x->nex->ch[i];
        }
    }
}
inline void Match(char *s){
    Node *x=root;
    int len=strlen(s+1);
    for(int i=1;i<=len;i++){
        x=x->ch[trans(s[i])];
        x->b=true;
        Node *tmp=x;
        while(tmp!=root && !tmp->nex->b) tmp->nex->b=true,tmp=tmp->nex;///将可以匹配的点标记
    }
}
int main(){
    len=read();m=read();
    scanf("%s",s+1);
    for(int i=1;i<=m;i++){
        scanf("%s",c+1);
        Insert(c,i);
    }
    GetFail();
    Match(s);
    for(int i=1;i<=m;i++){
        Node *x=tail[i];
        while(!x->b){
            x=x->pa;///往上爬,找第一个被标记过的点
        }
        printf("%d\n",x->dep);
    }
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值