ac自动机是kmp的高级版,实现多模式串匹配。
代码:
struct AC{
int next[500005][26], fail[500005], word[500005], Q[500005];
int root, tol;
int newNode(){
for(int i = 0; i < 26; i++)
next[tol][i] = -1;
word[tol++] = 0;
return tol - 1;
}
void Init(){
tol = 0;
root = newNode();
}
void Insert(char s[]){
int now = root;
for(int i = 0, k; s[i] ;i++){
k = s[i]-'a';
if(next[now][k] == -1)
next[now][k] = newNode();
now = next[now][k];
}
/*
根据要求对word进行处理
Solve(word[now])
*/
}
void build(){
int front, rear;
front = rear = 0;
for(int i=0;i<26;i++){
if(next[root][i]==-1)
next[root][i] = root;
else
{
fail[next[root][i]] = root;
Q[rear++] = next[root][i];
}
}
while(front < rear){
int now = Q[front++];
for(int i = 0; i < 26; i++){
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else{
fail[next[now][i]] = next[fail[now]][i];
Q[rear++]=next[now][i];
}
}
}
}
int Search(char s[]){
int now = root, res = 0;
for(int i = 0, k; s[i] ;i++){
k = s[i] - 'a';
now = next[now][k];
int tmp = now;
while(tmp != root){
/*
......
根据不同条件,获得不同的信息
......
*/
tmp = fail[tmp];
}
}
return res;
}
}ac;