您的位置:首页 > 其它

HDU 2222 Keywords Search ac自动机模板

2016-07-29 15:58 369 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2222

题意:给一些模式串,最后一个目标串,问目标串中模式串的个数

思路:ac自动机模板题,存个档

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define debug puts("here")
using namespace std;

const int N = 1000010;
struct node
{
node *fail;
node *next[26];
int cnt;
node()
{
fail = NULL;
memset(next, 0, sizeof next);
cnt = 0;
}
}*que
;
char s[60], str
;

void _insert(char *s, node *root)
{
node *p = root;
for(int i = 0; s[i]; i++)
{
int j = s[i] - 'a';
if(p -> next[j] == NULL)
p -> next[j] = new node();
p = p -> next[j];
}
p -> cnt++;
}
void create_fail(node *root)
{
int head = 0, tail = 0;
que[tail++] = root;
while(head != tail)
{
node *p = que[head++];
node *tmp = NULL;
for(int i = 0; i < 26; i++)
{
if(p -> next[i] != NULL)
{
if(p == root) p -> next[i] -> fail = root; //root的子节点的fail指针必定指向root
else
{
tmp = p -> fail;
while(tmp != NULL)
{
if(tmp -> next[i] != NULL) //找到匹配
{
p -> next[i] -> fail = tmp -> next[i];
break;
}
tmp = tmp -> fail;
}
if(tmp == NULL) p -> next[i] -> fail = root; //匹配为空则从root重新匹配
}
que[tail++] = p -> next[i];
}
}
}
}
int query(char *s, node *root)
{
int cnt = 0;
node *p = root;
for(int i = 0; s[i]; i++)
{
int j = s[i] - 'a';
while(p -> next[j] == NULL && p != root) //与当前点不匹配,跳转到失败指针
p = p -> fail;
p = p -> next[j];
if(p == NULL) p = root;
node *tmp = p;
while(tmp != root && tmp -> cnt != -1)
{
cnt += tmp -> cnt;
tmp -> cnt = -1;
tmp = tmp -> fail;
}
}
return cnt;
}
int main()
{
int t, n;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
node *root = new node;
for(int i = 0; i < n; i++)
{
scanf("%s", s);
_insert(s, root);
}
create_fail(root);
scanf("%s", str);
printf("%d\n", query(str, root));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: