HDU2222:Keywords Search(AC自动机模板)
Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 81284 Accepted Submission(s): 28367
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
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
题意:
问有多少个字符串能够匹配给出的那一个字符串。
题解:
多模式匹配问题,直接上AC自动机就好了。
代码如下:
#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <vector> #include <queue> using namespace std; typedef long long ll; const int N = 500005,M = 26; int t; int n; queue <int> q; char s[55],str[1000005]; struct Aho_Corasick{ int Size; int ch[N][M]; int val[N]; int fail[N]; void init(){ Size=-1; newnode(); } int newnode(){ memset(ch[++Size],0,sizeof(ch[0])); val[Size]=fail[Size]=0; return Size; } void insert(char *s){ int l=strlen(s); int u=0; for(int i=0;i<l;i++){ int idx=s[i]-'a'; if(!ch[u][idx]) ch[u][idx]=newnode(); u=ch[u][idx]; } val[u]++; } void Getfail(){ while(!q.empty()) q.pop(); for(int i=0;i<26;i++){ if(ch[0][i]) q.push(ch[0][i]); } while(!q.empty()){ int cur=q.front();q.pop(); for(int i=0;i<26;i++){ if(ch[cur][i]){ fail[ch[cur][i]]=ch[fail[cur]][i]; q.push(ch[cur][i]); }else{ ch[cur][i]=ch[fail[cur]][i]; } } } } int query(char *s){ int ans = 0,u = 0; int l=strlen(s); for(int i=0;i<l;i++){ int idx = s[i]-'a'; int cur = ch[u][idx]; int tmp=cur; while(tmp && val[tmp]>=0){ ans+=val[tmp]; val[tmp]=-1; tmp=fail[tmp]; } u=cur; } return ans ; } }ac; int main(){ scanf("%d",&t); while(t--){ ac.init(); scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%s",s); ac.insert(s); int l=strlen(s); } ac.Getfail(); scanf("%s",str); int ans = ac.query(str); printf("%d\n",ans); } return 0; }
重要的是自信,一旦有了自信,人就会赢得一切。