AC自动机

#include<iostream>  
#include<queue>  
#define Chr 26//字符最大个数  
using namespace std;  
struct Node{  
    int next[Chr],fail;  
    bool dang;  
    //fail 实际是跳到了当前字符串的最长后缀的节点处  
};  
Node node[300000];  
int tN,hash[300],N;  
void get_hash(){//注意大小写!!  
    for(int i=0;i<26;i++)hash[i+'A']=i;  
}  
void set_node(int x){  
    memset(node[x].next,0,sizeof(node[x].next));  
    node[x].fail=0;node[x].dang=0;  
}  
void insert(char *x){  
    int loc=0,i;  
    for(i=0;x[i];i++){  
        if(node[loc].next[hash[x[i]]]==0){  
            node[loc].next[hash[x[i]]]=tN;  
            set_node(tN++);  
        }  
        // loc为中间节点  
        loc=node[loc].next[hash[x[i]]];  
    }  
    node[loc].dang=1;// 现在loc为单词的最末节点  
}  
queue<int> que;  
void get_fail(){  
    que.push(0);  
    int temp,i,son,j;  
    while(que.size()){  
        temp=que.front();que.pop();  
        for(i=0;i<Chr;i++){  
            if(node[temp].next[i]==0){  
                node[temp].next[i]=node[node[temp].fail].next[i];  
                continue;  
            }  
            son=node[temp].next[i];  
            if(temp){  
                node[son].fail=node[node[temp].fail].next[i];  
                node[son].dang|=node[node[son].fail].dang;  
            }  
            que.push(son);  
        }  
    }  
}  
void ini(){
	get_hash();  
    tN=0;  
    set_node(tN++); 
}

使用方法:

1、ini();注意hash函数根据题目不同自己改一下,字符个数Chr也要相应改一下。

2、用insert(char*)插字符串;

3、get_fail();

好了。


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值