您的位置:首页 > 其它

HDOJ 2222: Keywords Search

2017-02-15 16:11 204 查看

Keywords Search

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 59360 Accepted Submission(s): 19520


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
Print how many keywords are contained in the description.

[align=left]Sample Input[/align]

1
5
she
he
say
shr
her
yasherhs

[align=left]Sample Output[/align]

3

[align=left]Author[/align]
Wiskey

[align=left]Recommend[/align]
lcy | We have carefully selected several similar problems for you: 2896 3065 2243 2825 3341

分析:

AC自动机模板题...

代码:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
//by NeighThorn
using namespace std;

const int maxn=1000000+5,maxm=50+5;

int n,cas,tot,head,tail,q[500000+5];

char s[maxn],word[maxm];

struct trie{
int cnt,fail,nxt[26];
}tr[500000+5];

inline void init(void){
for(int i=0;i<=tot;tr[i].fail=-1,tr[i].cnt=0,i++)
for(int j=0;j<26;j++)
tr[i].nxt[j]=0;
tot=0;
}

inline void insert(char *word){
int p=0,len=strlen(word);
for(int i=0;i<len;i++){
if(!tr[p].nxt[word[i]-'a'])
tr[p].nxt[word[i]-'a']=++tot;
p=tr[p].nxt[word[i]-'a'];
}
tr[p].cnt++;
}

inline void buildACM(void){
head=0,tail=0;q[0]=0;
while(head<=tail){
int id=q[head++],p=-1;
for(int i=0;i<26;i++)
if(tr[id].nxt[i]){
if(id){
p=tr[id].fail;
while(p!=-1){
if(tr[p].nxt[i]){
tr[tr[id].nxt[i]].fail=tr[p].nxt[i];
break;
}
p=tr[p].fail;
}
if(p==-1) tr[tr[id].nxt[i]].fail=0;
}
else
tr[tr[id].nxt[i]].fail=0;
q[++tail]=tr[id].nxt[i];
}
}
}

inline int query(void){
int i=0,ans=0,index,len=strlen(s),p=0;
while(s[i]){
index=s[i]-'a';
while(!tr[p].nxt[index]&&p) p=tr[p].fail;
p=tr[p].nxt[index];
int tmp=p;
while(tmp&&tr[tmp].cnt!=-1)
ans+=tr[tmp].cnt,tr[tmp].cnt=-1,tmp=tr[tmp].fail;
i++;
}
return ans;
}

signed main(void){
scanf("%d",&cas);
while(cas--){
tot=500000;init();
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%s",word),insert(word);
buildACM();
scanf("%s",s);
printf("%d\n",query());
}
return 0;
}


  

By NeighThorn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: