1
9
2016
0

【HDU2222】【Aho-Corasick自动机】Keywords Search

Keywords Search

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

 

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
Author
Wiskey
Recommend
lcy

Aho-Corasick自动机裸题,国内OJ的英文描述就是好懂!

看到阿当也在交这道题,借鉴代码作为模板:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
#define pa pair<int,int>
#define maxn 500005
using namespace std;
int tt,n,ans,tot;
int t[maxn][26],go[maxn],v[maxn];
bool used[maxn];
char s[1000005];
inline void insert()
{
	scanf("%s",s);
	int len=strlen(s),now=1;
	F(i,0,len-1)
	{
		int x=s[i]-'a';
		if (!t[now][x]) t[now][x]=++tot;
		now=t[now][x];
	}
	v[now]++;
}
inline void bfs()
{
	queue<int> q;
	q.push(1);
	while (!q.empty())
	{
		int x=q.front(),y,j;q.pop();
		F(i,0,25)
		{
			j=go[x];
			while (j&&!t[j][i]) j=go[j];
			if (t[x][i])
			{
				go[y=t[x][i]]=j?t[j][i]:1;
				q.push(y);
			}
			else t[x][i]=j?t[j][i]:1;
		}
	}
}
inline void calc(int j)
{
	while (j&&!used[j])
	{
		if (v[j]) ans+=v[j];
		used[j]=true;
		j=go[j];
	}
}
inline void find()
{
	int len=strlen(s),j=1;
	F(i,0,len-1)
	{
		int x=s[i]-'a';
		j=t[j][x];
		calc(j);
	}
}
int main()
{
	scanf("%d",&tt);
	while (tt--)
	{
		tot=1;ans=0;
		memset(t,0,sizeof(t));
		memset(v,0,sizeof(v));
		memset(go,0,sizeof(go));
		memset(used,false,sizeof(used));
		scanf("%d",&n);
		F(i,1,n) insert();
		bfs();
		scanf("%s",s);
		find();
		printf("%d\n",ans);
	}
}

 

Category: 字符串 | Tags: | Read Count: 484

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com