HDU2222 Keywords Search [AC自动机]
Posted cytus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU2222 Keywords Search [AC自动机]相关的知识,希望对你有一定的参考价值。
Keywords Search
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
Sample Output
Author
Wiskey
分析:
水一波$AC$自动机裸题。
直接上$AC$自动机模板就行了,记得清空数组,其他别想太多就好。
Code:
//It is made by HolseLee on 14th Aug 2018 //HDU2222 #include<bits/stdc++.h> using namespace std; const int N=5e5+7; int T,n,m,ans,tot,fail[N],team[N],t[N][26],val[N]; char s[N*2]; void ins(char *ch) { int len=strlen(ch),root=0,id; for(int i=0;i<len;++i){ id=ch[i]-‘a‘; if(!t[root][id]) t[root][id]=++tot; root=t[root][id]; } val[root]++; } void getfail() { int root=0,head=0,tail=0;; for(int i=0;i<26;++i){ if(t[root][i]){ fail[t[root][i]]=0; team[++tail]=t[root][i]; } } while(head<tail){ root=team[++head]; for(int i=0;i<26;++i){ if(t[root][i]){ fail[t[root][i]]=t[fail[root]][i]; team[++tail]=t[root][i]; } else t[root][i]=t[fail[root]][i]; } } } void quary() { int root=0,id; for(int i=0;i<m;++i){ id=s[i]-‘a‘; root=t[root][id]; for(int j=root;j&&~val[j];j=fail[j]) ans+=val[j],val[j]=-1; } } int main() { scanf("%d",&T); while(T--){ scanf("%d",&n); ans=tot=0; memset(t,0,sizeof(t)); memset(val,0,sizeof(val)); memset(fail,0,sizeof(fail)); memset(team,0,sizeof(team)); for(int i=1;i<=n;++i){ scanf("%s",s);ins(s); } getfail(); scanf("%s",s); m=strlen(s); quary(); printf("%d ",ans); } return 0; }
以上是关于HDU2222 Keywords Search [AC自动机]的主要内容,如果未能解决你的问题,请参考以下文章