hdu 2222 Keywords Search
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 2222 Keywords Search相关的知识,希望对你有一定的参考价值。
Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
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
#include<cstdio> #include<queue> #include<cstring> using namespace std; #define abc 26 #define maxn 1000010 struct node { int count; node* fail;node* next[abc]; node () { fail=NULL; memset(next,0,sizeof(next)); count=0; } }; typedef node* a; queue<a>q; a root=NULL; char key[abc<<1],s[maxn]; void Build_AC(a root) { root->fail=NULL;q.push(root); while(!q.empty()) { a tp=q.front(),p;q.pop(); for(int i=0;i<abc;i++) if(tp->next[i]!=NULL) { if(tp==root) tp->next[i]->fail=root; else { for(p=tp->fail;p!=NULL;p=p->fail) if(p->next[i]!=NULL) { tp->next[i]->fail=p->next[i]; break; } if(p==NULL) tp->next[i]->fail=root; } q.push(tp->next[i]); } } } void insert(char s[],a root) { a p=root; for(int i=0,index;s[i];i++,p=p->next[index]) if(!p->next[index=s[i]-‘a‘])p->next[index]=new node; p->count++; } int query(a root) { int cnt=0;a p=root; for(int i=0,index;s[i];i++) { for(;p->next[index=s[i]-‘a‘]==NULL&&p!=root;p=p->fail); p=p->next[index]==NULL?root:p->next[index]; for(a tp=p;tp!=root&&tp->count!=-1;tp=tp->fail) cnt+=tp->count,tp->count=-1; } return cnt; } int main() { int n,q; scanf("%d",&q); while(q--) { root=new node; scanf("%d",&n); while(n--) { scanf("%s",key); insert(key,root); } Build_AC(root); scanf("%s",s); printf("%d\n",query(root)); } return 0; }
以上是关于hdu 2222 Keywords Search的主要内容,如果未能解决你的问题,请参考以下文章