您的位置:首页 > 其它

HDU 2222 Keywords Search(AC自动机模板)

2017-08-11 01:00 555 查看
题意:给你n个字符串,最后一行输入一个字符串,问最后一个字符串中出现了几个前面的字符串。

思路:AC自动机模板题。AC自动机详解见点击打开链接

模板:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

/****************************************************/
const int LetterSize = 26;
const int TrieSize = 10000*50+5;

int tot, root, fail[TrieSize], val[TrieSize], Next[TrieSize][LetterSize];
int newnode(void)
{
memset(Next[tot], -1, sizeof(Next[tot]));
val[tot] = 0;
return tot++;
}

void init(void)
{
tot = 0;
root = newnode();
}

int getidx(char x)
{
return x-'a';
}

void insert(char *ss)
{
int len = strlen(ss);
int now = root;
for(int i = 0; i < len; i++)
{
int idx = getidx(ss[i]);
if(Next[now][idx] == -1)
Next[now][idx] = newnode();
now = Next[now][idx];
}
val[now]++; //和Trie一样,根据需要而变
}

void build(void)
{
queue<int> Q;
fail[root] = root;
for(int i = 0; i < LetterSize; i++)
{
if(Next[root][i] == -1)
Next[root][i] = root;
else
fail[Next[root][i]] = root, Q.push(Next[root][i]);
}
while(!Q.empty())
{
int now = Q.front(); Q.pop();
for(int i = 0; i < LetterSize; i++)
{
if(Next[now][i] == -1)
Next[now][i] = Next[fail[now]][i];
else
fail[Next[now][i]] = Next[fail[now]][i], Q.push(Next[now][i]);
}
}
}

int match(char *ss)
{
int len = strlen(ss), now = root, res = 0;
for(int i = 0; i < len; i++)
{
int idx = getidx(ss[i]);
int tmp = now = Next[now][idx];
while(tmp)
{
res += val[tmp];
val[tmp] = 0;
tmp = fail[tmp];
}
}
return res;
}

/*************************************************/
const int maxn = 1e6+5;
char str[maxn], tmp[maxn];

int main(void)
{
int t, n;
cin >> t;
while(t--)
{
init();
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf(" %s", tmp), insert(tmp);
build();
scanf(" %s", str);
printf("%d\n", match(str));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU AC自动机 字符串