HDU 2222 Keywords Search

来源:互联网 发布:淘宝开两家店 编辑:程序博客网 时间:2024/06/07 02:29

Keywords Search

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


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
15shehesayshrheryasherhs
 

Sample Output
3


【题目分析】

    裸裸的自动机,但是第一次写这一个还是很痛苦的。敲了奖金2个小时才明白了一丢丢。现在还是没有完全理解。

    其实fail指针就像是KMP中next指针一样,顺着整个字符串往上爬。而fail是顺着整棵树向上寻找。

    只要写出AC自动机,然后记录每个节点的结束的字符串数,然后在记录下是否达到这个节点,还有一点的就是,匹配完成之后,需要用fail指针把向上的失配点扫描一遍。只有这样,才能保证补不缺不漏。

写的过程中借助了阿当的代码:http://blog.csdn.net/aarongzk/article/details/50486001


【代码】

#include <cstdio>#include <iostream>#include <cstring>#include <queue>using namespace std;#define M(a) memset(a,0,sizeof a)#define F(i,j,k) for (int i=j;i<=k;++i)int trie[500005][26],fail[500005],vis[500005],w[500005];char s[1000001];int T,t,n,tot,ans;void insert(){scanf("%s",s);int now=1,l=strlen(s)-1;F(i,0,l){if (!trie[now][s[i]-'a']) trie[now][s[i]-'a']=++tot;now=trie[now][s[i]-'a'];}w[now]++;}void getfail(){queue <int> q;q.push(1);while (!q.empty()){int y,j,x=q.front();q.pop();F(i,0,25){j=fail[x];while (j&&!trie[j][i]) j=fail[j];if (trie[x][i]){fail[trie[x][i]]=j?trie[j][i]:1;q.push(trie[x][i]);}else trie[x][i]=j?trie[j][i]:1;}}}void find(){int l=strlen(s)-1,now=1;F(i,0,l){now=trie[now][s[i]-'a'];int k=now;while (now&&!vis[now]){vis[now]=true;ans+=w[now];now=fail[now];}now=k;}}int main(){scanf("%d",&T);while (T--){tot=1,ans=0;M(trie);M(fail);M(vis);M(w);scanf("%d",&n);F(i,1,n) insert();getfail();scanf("%s",s);find();printf("%d\n",ans);}}


0 0
原创粉丝点击