您的位置:首页 > 其它

AC自动机 多模式串匹配 模板

2016-10-18 01:51 351 查看
AC自动机就是字典树+KMP,解决了一个串在字典树中的匹配问题。

const int maxn = 26;
struct node{
node* fail;  node* next[maxn];
int counts;
node(){
fail = NULL;
counts = 0;
for(int i = 0; i < maxn; ++i)
next[i] = NULL;
}
};

struct Trie{
node* root;
queue<node*> q;
Trie(){root = NULL;}

void inserts(char str[]){
int len = strlen(str);
if(!root)
root = new node;
node* now = root;
for(int i = 0; i < len; ++i){
int idx = str[i]-'a';//transform
if(now->next[idx] == NULL)
now->next[idx] = new node;
now = now->next[idx];
}
++(now->counts);//the counts of the words that suffix match
}
void build_fail(){
root->fail = NULL;
q.push(root);
while(!q.empty()){
node* now = q.front();  q.pop();
node* jump = NULL;
for(int i = 0; i < maxn; ++i){
if(now->next[i] != NULL){
jump = now->fail;
while(jump != NULL){
if(jump->next[i] != NULL){//equal
now->next[i]->fail = jump->next[i];
break;
}
jump = jump->fail;
}
if(jump == NULL)//reach root
now->next[i]->fail = root;
q.push(now->next[i]);
}
}
}
}
int query(char str[]){//return the count of the Tree-words in str
int ans = 0, idx, len = strlen(str);
node* p = root;
for(int i = 0; i < len; ++i){
idx = str[i]-'a';////transform
while(p->next[idx]==NULL && p!=root)
p = p->fail;
p = (p->next[idx]==NULL) ? root : p->next[idx];
node* jump = p;
while(jump != root && jump->counts > 0){//find the words that suffix match
ans += jump->counts;
jump->counts = 0;//avoid repeat
jump = jump->fail;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: