您的位置:首页 > 其它

【HDU2222】Keywords Search

2016-01-21 21:34 330 查看
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

首先要说一下这个题号,2222,hhh。

其次这是一道AC自动机的裸题,但不知为何我第一次打AC自动机打成了爱吃自动机。。。其实这个名字也挺好

黄学长的代码写的很优美,这里就不再多说些什么了。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char ch[51],s[1000001];
int T,n,sz,ans;
int a[500001][27],q[500001],point[500001],danger[500001];
bool mark[500001];

void insert(){
int len=strlen(ch),now=1;
for (int i=0;i<len;i++){
int t=ch[i]-'a'+1;
if (a[now][t])now=a[now][t];
else now=a[now][t]=++sz;
}
danger[now]++;//判断单词是否出现
}

void acmach(){//构建AC自动机
int h=0,t=1;
q[0]=1;point[1]=0;
while (h<t){
int now=q[h++];
for (int i=1;i<=26;i++){
if (!a[now][i]) continue;
int k=point[now];
while(!a[k][i])k=point[k];
point[a[now][i]]=a[k][i];//这里是失败指针,类似KMP
q[t++]=a[now][i];
}
}
}

void solve(){
int len=strlen(s),k=1;
for (int i=0;i<len;i++){
mark[k]=1;
int t=s[i]-'a'+1;
while (!a[k][t])k=point[k];
k=a[k][t];
if (!mark[k])
for (int j=k;j;j=point[j]){
ans+=danger[j];
danger[j]=0;//因为有多组数据
}
}
printf("%d\n",ans);
}

int main(){
scanf("%d",&T);
while (T--){
sz=1;ans=0;
scanf("%d",&n);
for (int i=1;i<=26;i++)a[0][i]=1;
for (int i=1;i<=n;i++){
scanf("%s",ch);
insert();
}
acmach();
scanf("%s",s);
solve();
for(int i=1;i<=sz;i++){
point[i]=danger[i]=mark[i]=0;
for(int j=1;j<=26;j++)a[i][j]=0;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: