您的位置:首页 > 其它

hdu 2222 Keywords Search

2017-04-30 21:19 405 查看
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

【分析】

题意:给n个单词和一个文章,求文章中出现了多少个单词。

AC自动机裸题…讲解参考http://www.cnblogs.com/hate13/p/4348781.html

代码参考

http://www.cnblogs.com/KonjakJuruo/p/5686398.html

(ps:这位同学的代码看上去超亲切的…)

【代码】

//hdu 2222
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
queue <int> q;
const int mxn=1000005;
char s[mxn];
int T,num,n;
struct node
{
int son[30];
int fail,cnt;  //cnt:以该节点为结尾的单词个数
}a[mxn];
inline void clear(int x)
{
a[x].fail=a[x].cnt=0;
memset(a[x].son,0,sizeof a[x].son);
}
inline void trie()
{
int x=0,len=strlen(s);
fo(i,0,len-1)
{
int t=s[i]-'a'+1;
if(!a[x].son[t])
{
num++;
clear(num);
a[x].son[t]=num;
}
x=a[x].son[t];
}
a[x].cnt++;
}
inline void build()
{
while(!q.empty()) q.pop();
fo(i,1,26)
if(a[0].son[i]) q.push(a[0].son[i]);
while(!q.empty())
{
int x=q.front();q.pop();
int fail=a[x].fail;
fo(i,1,26)
{
int y=a[x].son[i];
if(y)
{
a[y].fail=a[fail].son[i];
q.push(y);
}
else a[x].son[i]=a[fail].son[i]; //???
}
}
}
inline int find()  //文本串找单词
{
int x=0,ans=0,len=strlen(s);
fo(i,0,len-1)
{
int t=s[i]-'a'+1;
while(x && !a[x].son[t]) x=a[x].fail;
x=a[x].son[t];
int p=x;
while(p && a[p].cnt!=-1)
{
ans+=a[p].cnt;
a[p].cnt=-1;
p=a[p].fail;
}
}
return ans;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
num=0;
clear(0);
fo(i,1,n)
{
scanf("%s",s);
trie();
}
build();
scanf("%s",s);
printf("%d\n",find());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: