#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define N 1000010
#define WORD_SIZE 26
#define WORD_START 'a'
using namespace std;
class Node
{
public :
int next[WORD_SIZE];
int count;
int fail;
};
class AC_automation
{
public :
Node tree[N];
int cur_id;
int q[N];
int root;
AC_automation()
{
cur_id = 0;
root = 0;
init_node(root);
}
void insert_word( char *str );
void init_node( int p );
void build_AC( int p );
void clear();
int query_word( char *s, int p );
};
void AC_automation::clear()
{
cur_id = 0;
root = 0;
init_node(root);
}
void AC_automation::init_node( int p )
{
for( int i = 0; i < WORD_SIZE; i ++ )
{
tree[p].next[i] = -1;
}
tree[p].count = 0;
tree[p].fail = -1;
}
void AC_automation::insert_word( char *str )
{
int p = root, u;
while( *str )
{
u = *str - WORD_START;
if( tree[p].next[u] == -1 )
{
init_node(++cur_id);
tree[p].next[u] = cur_id;
}
p = tree[p].next[u];
str++;
}
tree[p].count++;
}
void AC_automation::build_AC( int p )
{
int front = 0, rear = 0, t;
tree[p].fail = root;
q[ rear++] = p;
while( front != rear )
{
p = q[ front ++];
for( int i = 0; i < WORD_SIZE; i ++ )
{
if( tree[p].next[i] != -1 )
{
if( p == root ) tree[ tree[p].next[i] ].fail = root;
else
{
t = tree[p].fail;
while( t != root && tree[t].next[i] == -1 ) t = tree[t].fail;
if( tree[t].next[i] != -1 ) tree[ tree[p].next[i] ].fail = tree[t].next[i];
else tree[ tree[p].next[i] ].fail = root;
}
q[ rear ++ ] = tree[p].next[i];
}
}
}
}
int AC_automation::query_word( char *s, int p )
{
int u,q, ans = 0;
while( *s )
{
u = *s - WORD_START;
while( p != root && tree[p].next[u] == -1 ) p = tree[p].fail;
p = tree[p].next[u];
if( p == -1 ) p = root;
q = p;;
while( q!=root && tree[q].count != -1 )
{
ans += tree[q].count;
tree[q].count = -1;
q = tree[q].fail;
}
s++;
}
return ans;
}
char s[N];
AC_automation AC;
int main()
{
int cas,n;
char str[55];
scanf("%d",&cas);
while( cas -- )
{
AC.clear();
scanf("%d",&n);
while( n -- )
{
scanf("%s",str);
AC.insert_word(str);
}
AC.build_AC(AC.root);
scanf("%s",s);
printf("%d\n",AC.query_word( s, AC.root) );
}
return 0;
}
hdu 2222
最新推荐文章于 2020-02-09 21:45:15 发布