AC自动机

AC自动机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// main.cpp
#include<iostream>
#include<queue>
#include<string>
#include "AcAuto.h"
using namespace std;
void insert(Node&,string&);
void build_ac_automation(Node&);
int query(Node& root, string& s);
static int Scount = 0;
int main()
{
string key;
string str;
cout << "输入单词" << endl;
Node root;
for (int i = 0; i < 4; i++)
{
cin >> key;//输入单词
insert(root, key);
}
build_ac_automation(root);
cout << "输入模式串" << endl;
cin >> str;//输入模式串
query(root, str);
cout << Scount << endl;
return 0;
}
void insert(Node& root,string& s)
{
int i = 0,index;
Node* temp = &root;
while (i<s.size())//如果没这个节点,创建
{
index = s[i] - 'a';
if (temp->next[index] == NULL)
{
temp->next[index] = new Node();
}
temp = temp->next[index];
i++;
}
temp->flag = true;//最后一个单词
temp->count++;
}
void build_ac_automation(Node& root)//建立fail指针,如果当前节点不匹配,去找前缀相同的其他节点
{
Node* T = &root;
queue<Node*> q;
q.push(&root);
while (!q.empty())//深度优先搜索,建立,这样才能建立起前缀的fail指针
{
Node* t_fail = NULL;
T = q.front();
q.pop();
for (int i = 0; i < 26; i++)//DFS26个子节点
{
if (T->next[i])
{
if (T == &root)//如果是第一层节点
T->next[i]->fail = &root;
else
{
t_fail = T->fail;
while (t_fail)
{
if (t_fail->next[i])
{
T->next[i]->fail = t_fail->next[i];
break;
}
t_fail = t_fail->fail;
}
if (t_fail == NULL)
{
T->next[i]->fail = &root;
}
}
q.push(T->next[i]);
}
}
}
}
int query(Node& root, string& s)
{
int pos = 0,i=0;
Node* T = &root;
while (i<s.size())
{
pos = int(s[i] - 'a');
while (T->next[pos] == NULL && T != &root)
{
T = T->fail;
}
T = T->next[pos];
T = (T == NULL) ? &root : T;
if (T->flag&&T->count!=-1)
{
T->count = -1;
Scount++;
}
i++;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
\\AC.cpp
#include "AcAuto.h"
#include<iostream>
using namespace std;
Node::Node()
{
flag = false;
count = 0;
fail = NULL;
memset(next, NULL, sizeof(next));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#AC.h
#pragma once
#ifndef Ac_Auto
#define Ac_Auto
#include <string>
const int kid = 26;
struct Node
{
public:
Node* fail;
Node* next[kid];
int count;
bool flag;//判断是否到最后一个节点,即是否完全匹配
Node();
};
#endif // !Ac_Auto