要学会AC自己主动机,我们必须知道什么是Trie。也就是字典树。最好对KMP算法也有些了解。Trie树和KMP算法我之前博客都有写过。感兴趣的能够看看。
简单叙述下问题,如今给出
"hsay";
"ah";
"sahe";
"he";
"say";
"herhb";
"aher";
"erhs"
共8个关键词。要问字符串"yasaherhsay"中这8个关键词有几个出现过。
答案是7。
这就是一个多模式匹配问题。
AC自己主动机算法分为3步:构造一棵Trie树。构造失败指针和模式匹配过程。
失败指针和KMP算法中的next函数或称shift函数的功能类似。
上图解释了失败指针的作用。
// AC_automachine.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<vector>
#include<algorithm>
#include<set>
#include<iostream>
using namespace std;
#define MAXSIZE 26
struct TrieNode
{
TrieNode* next[MAXSIZE];
TrieNode*parent;
vector<TrieNode*>fail;
char p;
int Num;
bool isword;
};
set<string>re;//保存结果
TrieNode*initiate_Trie()
{
TrieNode*root = new TrieNode;
for (int i = 0; i < MAXSIZE; i++)
root->next[i] = NULL;
root->Num = 0;
root->parent = NULL;
root->isword = false;
return root;
}
bool search(TrieNode*root, char*str)
{
TrieNode*tn;
tn = root;
int k;
while (*str != '