#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<vector>
using namespace std;
typedef struct _node {
vector<int> exist;
_node* fail;
_node* child[26];
}node;
//const char* p[] = { "he","she","hers","his" };
vector<string>p;
const char* T = "ahishers";
int trie[100010][26];
queue<node*>q;
void insert(node* &root, string s)
{
node* p = root;
for (int i = 0; i < s.size(); i++)
{
int c = s[i] - 'a';
if (p->child[c] == NULL)
{
node* k = new node;
for (int j = 0; j < 26; j++) k->child[j] = NULL;
k->exist.clear(); k->fail = NULL;
p->child[c] = k;
}
p = p->child[c];
}
p->exist.push_back(s.size());
}
void build(node* &root)
{
node* fafail;
int n = p.size();
for (int i = 0; i < n; i++)
{
insert(root, p[i]);
}
for (int i = 0; i < 26; i++)
{
if (root->child[i])
{
q.push(root->child[i]);
root->child[i]->fail = root;
}
}
while (!q.empty())
{
node* x = q.front();
q.pop();
for (int i = 0; i < 26; i++)
{
node* y;
if (x->child[i])
{
y = x->child[i];
fafail = x->fail;
while (fafail&&fafail->child[i] == NULL)
{
fafail = fafail->fail;
}
if (fafail == NULL)
{
y->fail = root;
}
else
{
y->fail = fafail->child[i];
if (y->fail->exist.size())
{
for (int j = 0; j < y->fail->exist.size(); j++)
{
y->exist.push_back(y->fail->exist[j]);
}
}
}
q.push(y);
}
}
}
}
void query(node* &root)
{
node* tmp = root;
for (int i = 0; i < strlen(T); i++)
{
int c = T[i] - 'a';
while (tmp->child[c] == NULL && tmp->fail) tmp = tmp->fail;
if (tmp->child[c]) tmp = tmp->child[c];
else continue;
if (tmp->exist.size())
{
for (int j = 0; j < tmp->exist.size(); j++)
{
int len = tmp->exist[j];
printf("查找位置=%d,长度=%d", i - len + 1, len);
}
}
}
}
int main()
{
node* root = new node;
for (int i = 0; i < 26; i++) root->child[i] = NULL;
root->fail = NULL;
root->exist.clear();
p.push_back("he");
p.push_back("she");
p.push_back("hers");
p.push_back("his");
build(root);
query(root);
return 0;
}
【模板】AC自动机
最新推荐文章于 2023-11-21 17:02:42 发布