HD2222 Keywords Search(AC自动机入门题)

然而还不是很懂=_=

 #include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
using namespace std;
const int Max = +;
char str[Max];
struct node
{
int cnt;
struct node * Next[];
struct node * fail;
void init()
{
for (int i = ; i < ; i++)
Next[i] = NULL;
cnt = ;
fail = NULL;
}
};
node * root;
void Insert()
{
node * p = root;
int len = strlen(str);
for (int i = ; i < len; i++)
{
int id = str[i] - 'a';
if (p->Next[id] == NULL)
{
p->Next[id] = new node();
p->Next[id]->init();
}
p = p->Next[id];
}
p->cnt++;
}
void getFail()
{
node * p = root, *temp, *son;
queue<struct node * > que;
que.push(p);
while (!que.empty())
{
temp = que.front();
que.pop();
for (int i = ; i < ; i++)
{
son = temp->Next[i];
if (son != NULL)
{
if (temp == root)
{
son->fail = root;
}
else
{
p = temp->fail;
while (p)
{
if (p->Next[i])
{
son->fail = p->Next[i];
break;
}
p = p->fail;
}
if (!p)
son->fail = root;
}
que.push(son);
}
}
}
}
void querry()
{
int len, cnt = ;
len = strlen(str);
node * p, * temp;
p = root;
for (int i = ; i < len; i++)
{
int pos = str[i] - 'a';
while (!p->Next[pos] && p != root)
p = p->fail;
p = p->Next[pos];
if (!p)
p = root;
temp = p;
while (temp != root)
{
if (temp->cnt >= )
{
cnt += temp->cnt;
temp->cnt = -;
}
else
break;
temp = temp->fail;
}
}
printf("%d\n", cnt);
}
int main()
{
int test, n;
scanf("%d", &test);
while (test--)
{
root = new node();
root->init();
root->fail = NULL;
scanf("%d", &n);
getchar();
for (int i = ; i < n; i++)
{
gets(str);
Insert();
}
getFail();
gets(str);
querry();
}
return ;
}
上一篇:Linux 常见命令


下一篇:oracle 导出导入表