【HDU2222】Keywords Search(AC自动机)

时间:2023-03-09 02:57:10
【HDU2222】Keywords Search(AC自动机)
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
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
【题意】
  给你很多个单词,然后给你一篇文章,问给出的单词在文章中出现的次数。
【分析】
  根据输入的串建AC自动机,不断走fail累加即可。
注意理解题意,同一个串出现一次只算一次,给几个比较坑的数据:
4

5
she
he
say
shr
her
yasherhs 5
she
he
say
shr
her
yasherhs 3
she
she
she
shesheshe 6
she
he
he
say
shr
her
yasherhs 答案:
3
3
3
4

  

代码如下:

 #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define Maxn 800100
#define Maxl 60 char s[Maxl];
char ss[]; struct node
{
int son[],cnt,fail;
}t[Maxn];int tot; void upd(int x)
{
t[x].cnt=;
memset(t[x].son,,sizeof(t[x].son));
} void read_trie()
{
int n;
scanf("%d",&n);
tot=;upd();
for(int i=;i<=n;i++)
{
int now;
scanf("%s",s+);
int len=strlen(s+);
now=;
for(int j=;j<=len;j++)
{
int ind=s[j]-'a'+;
if(!t[now].son[ind])
t[now].son[ind]=++tot,upd(tot);
now=t[now].son[ind];
if(j==len) t[now].cnt++;
}
}
} queue<int > q;
void build_AC()
{
int i,j,x,y;
while(!q.empty()) q.pop();
q.push();
while(!q.empty())
{
x=q.front();
y=t[x].fail;
for(j=;j<=;j++)
{
if(t[x].son[j])
{
q.push(t[x].son[j]);
t[t[x].son[j]].fail=x?t[y].son[j]:x;
}
else t[x].son[j]=t[y].son[j];
}
q.pop();
}
} int gmark(int x,int y)
{
if(!x) return y;
if(t[x].cnt) y+=t[x].cnt,t[x].cnt=;
return gmark(t[x].fail,y);
} void ffind()
{
scanf("%s",ss+);
int l=strlen(ss+);
int now,ans=;
for(int i=;i<=l;i++)
{
int x=ss[i]-'a'+;
now=t[now].son[x];
ans+=gmark(now,);
}
printf("%d\n",ans);
} int main()
{
int T;
scanf("%d",&T);
while(T--)
{
read_trie();
build_AC();
ffind();
}
return ;
}

[HDU2222]

2016-06-14 17:02:09