#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();
好了。