请用c加加编写AC自动机的代码
时间: 2023-08-31 13:27:47 浏览: 129
AC自动机代码
### 回答1:
您可以使用C++编写AC自动机的代码。请参考以下示例代码:
```cpp
#include <iostream>
#include <string>using namespace std;int main()
{
string pattern, text;
cout << "Enter the pattern to be searched: ";
cin >> pattern;
cout << "Enter the text in which to search: ";
cin >> text; int i, j;
int m = pattern.length();
int n = text.length(); for (i = 0; i <= n - m; i++)
{
j = 0;
while (j < m && pattern[j] == text[i + j])
j++; if (j == m)
cout << "Pattern found at position " << i << endl;
}
return 0;
}
```
### 回答2:
AC自动机是一种多模式字符串匹配算法,可以在输入的文本中同时查找多个模式(关键词)的出现位置,其基本思想是构建一个有限状态自动机来处理模式匹配。
以下是用C++编写AC自动机的代码示例:
```cpp
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAX_NODE = 10000; // 最大节点数
const int MAX_WORD_LENGTH = 100; // 最大模式串长度
struct TrieNode {
int child[26]; // 字符集大小为26,表示子节点的索引
int fail; // 失败指针,指向匹配失败后的跳转节点
int cnt; // 记录当前节点对应的模式串出现的次数
bool isWord; // 当前节点是否是一个模式串的结尾
TrieNode() {
memset(child, -1, sizeof(child));
fail = -1;
cnt = 0;
isWord = false;
}
};
TrieNode trie[MAX_NODE]; // Trie树
int nodeCount = 0;
void insertTrie(const string& word) {
int node = 0;
for (char c : word) {
int idx = c - 'a';
if (trie[node].child[idx] == -1) {
trie[node].child[idx] = ++nodeCount;
}
node = trie[node].child[idx];
}
trie[node].isWord = true;
}
void buildAC() {
queue<int> q;
for (int i = 0; i < 26; i++) {
if (trie[0].child[i] != -1) {
trie[trie[0].child[i]].fail = 0;
q.push(trie[0].child[i]);
}
}
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < 26; i++) {
if (trie[cur].child[i] != -1) {
int child = trie[cur].child[i];
int fail = trie[cur].fail;
while (fail != -1 && trie[fail].child[i] == -1) {
fail = trie[fail].fail;
}
if (fail == -1) {
trie[child].fail = 0;
} else {
trie[child].fail = trie[fail].child[i];
}
q.push(child);
}
}
}
}
int matchAC(const string& text) {
int cur = 0;
int count = 0;
for (char c : text) {
int idx = c - 'a';
while (cur != 0 && trie[cur].child[idx] == -1) {
cur = trie[cur].fail;
}
cur = trie[cur].child[idx];
if (cur == -1) {
cur = 0;
}
int temp = cur;
while (temp != 0) {
if (trie[temp].isWord) {
count += trie[temp].cnt;
trie[temp].cnt = 0; // 防止重复计数
}
temp = trie[temp].fail;
}
}
return count;
}
int main() {
ios::sync_with_stdio(false);
int patternCount;
cin >> patternCount;
for (int i = 0; i < patternCount; i++) {
string pattern;
cin >> pattern;
insertTrie(pattern);
}
buildAC();
string text;
cin >> text;
int count = matchAC(text);
cout << count << endl;
return 0;
}
```
以上是一个简单的AC自动机的实现,通过构建Trie树并利用队列实现BFS求解失败指针,可以在输入的文本中统计各个模式串的出现次数,并输出统计结果。
阅读全文