您的位置:首页 > 其它

hdu 2222Keywords Search(AC自动机入门好题)

2017-08-18 20:38 357 查看


Keywords Search


Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/131072K (Java/Other)


Total Submission(s) : 2   Accepted Submission(s) : 2


Font: Times New Roman | Verdana | Georgia


Font Size: ← →


Problem Description

In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.

Wiskey also wants to bring this feature to his image retrieval system.

Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.

To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.


Input

First line will contain one integer means how many cases will follow by.

Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)

Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.

The last line is the description, and the length will be not longer than 1000000.


Output

Print how many keywords are contained in the description.


Sample Input

1
5
she
he
say
shr
her
yasherhs



Sample Output

3



Author

Wiskey

想法:AC自动机模板

代码:

#include<queue>
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define sz 26
#define N 1000000
int T, n;
char str
, key[55];
struct Node
{
Node *fail, *nxt[sz];
int cnt;
Node()
{
fail=NULL, cnt=0;
for(int i=0; i<sz; i++)
nxt[i]=NULL;
}
} *root;
void insert( char *s )
{
int tmp, len=strlen(s);
Node *p=root;
for ( int i=0; i<len; i++ )
{
tmp=s[i]-'a';
if( p->nxt[tmp]==NULL )
p->nxt[tmp]=new Node();
p=p->nxt[tmp];
}
p->cnt++;
}
int find()
{
int tmp, len=strlen(str), ans=0;
Node *p=root;
for ( int i=0; i<len; i++ )
{
tmp=str[i]-'a';
while( p->nxt[tmp]==NULL&&p!=root) p=p->fail;
p=p->nxt[tmp];
if(p==NULL) p=root;
Node *q=p;
while( q!=root && q->cnt!=-1 )
ans+=q->cnt, q->cnt=-1, q=q->fail;
}
return ans;
}
void build_Fail()
{
queue<Node *>q;
q.push(root);
while(!q.empty())
{
Node *p=q.front(), *tmp; q.pop();
for ( int i=0; i<sz; i++ )
if( p->nxt[i]!=NULL )
{
if( p==root ) p->nxt[i]->fail=root;
else
{
tmp=p->fail;
while( tmp!=NULL )
{
if( tmp->nxt[i]!=NULL )
{
p->nxt[i]->fail=tmp->nxt[i];
break;
}
tmp=tmp->fail;
}
if( tmp==NULL )
p->nxt[i]->fail=root;
}
q.push(p->nxt[i]);
}
}
}
int main()
{
scanf("%d", &T);
while(T--)
{
root=new Node();
scanf("%d",&n); getchar();
for( int i=1; i<=n; i++ )
gets(key), insert(key);
build_Fail();
scanf("%s", str);
printf("%d\n", find());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: