标签:hdu2222 keywords search ac自动机 字符串
1 5 she he say shr her yasherhs
3
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#define SIZE 1000100
using namespace std ;
struct Trie{
int count ;
Trie *fail ;
Trie *next[26] ;
Trie()
{
for(int i = 0 ; i < 26 ; ++i)
next[i] = NULL ;
fail = NULL ;
count = 0 ;
}
} *root ;
char des[SIZE] ;
void insert(char ch[])
{
int len = strlen(ch) ;
Trie *t = root ;
for(int i = 0 ; i < len ; ++i)
{
if(t->next[ch[i]-'a'] == NULL)
{
t->next[ch[i]-'a'] = new Trie() ;
}
t = t->next[ch[i]-'a'] ;
}
t->count++ ;
}
void bfs()
{
queue<Trie*> que ;
que.push(root) ;
while(!que.empty())
{
Trie *t = que.front() ;
que.pop() ;
for(int i = 0 ; i < 26 ; ++i)
{
if(t->next[i] != NULL)
{
if(t == root)
t->next[i]->fail = root ;
else
{
Trie *p = t->fail ;
while( p )
{
if(p->next[i])
{
t->next[i]->fail = p->next[i] ;
break ;
}
p = p->fail ;
}
if(p == NULL)
t->next[i]->fail = root ;
}
que.push(t->next[i]) ;
}
}
}
}
int query(char str[])
{
int sum = 0 , i = 0;
Trie *now = root ;
while(str[i])
{
int pos = str[i]-'a' ;
while(now->next[pos] == NULL && now != root)
{
now = now->fail ;
}
now = now->next[pos] ;
if(!now)
now = root ;
Trie *temp = now ;
while(temp != root)
{
if(temp->count>=0)
{
sum += temp->count ;
temp->count = -1 ;
}
else break ;
temp = temp->fail ;
}
++i ;
}
return sum ;
}
void del(Trie *t)
{
for(int i = 0 ; i < 26 ; ++i)
{
if(t->next[i])
del(t->next[i]) ;
}
free(t) ;
}
int main()
{
int t ;
scanf("%d",&t) ;
while(t--)
{
root = new Trie() ;
int n ;
scanf("%d",&n);
getchar() ;
for(int i = 0 ; i < n ; ++i)
{
char str[100] ;
gets(str) ;
insert(str) ;
}
bfs() ;
gets(des) ;
int ans = query(des) ;
printf("%d\n",ans) ;
del(root) ;
}
return 0 ;
}hdu 2222 Keywords Search AC自动机模板题
标签:hdu2222 keywords search ac自动机 字符串
原文地址:http://blog.csdn.net/lionel_d/article/details/45194383