码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 2222 Keywords Search

时间:2017-05-14 12:20:26      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:fail   sys   modern   bottom   each   engine   printf   inpu   int   

Keywords Search

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)

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自动机水之。
喜闻乐见的Code
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define abc 26
#define maxn 1000010
struct node {
	int count;
	node* fail;node* next[abc];
	node () {
		fail=NULL;
		memset(next,0,sizeof(next));
		count=0;
	}
};
typedef node* a;
queue<a>q;
a root=NULL;
char key[abc<<1],s[maxn];
void Build_AC(a root) {
	root->fail=NULL;q.push(root);
	while(!q.empty()) {
		a tp=q.front(),p;q.pop();
		for(int i=0;i<abc;i++)
			if(tp->next[i]!=NULL) {
				if(tp==root) tp->next[i]->fail=root;
				else {
					for(p=tp->fail;p!=NULL;p=p->fail)
						if(p->next[i]!=NULL) {
							tp->next[i]->fail=p->next[i];
							break;
						}
					if(p==NULL) tp->next[i]->fail=root;
				}
				q.push(tp->next[i]);
			}
	}
}
void insert(char s[],a root) {
	a p=root;
	for(int i=0,index;s[i];i++,p=p->next[index])
		if(!p->next[index=s[i]-‘a‘])p->next[index]=new node;
	p->count++;
}
int query(a root) {
	int cnt=0;a p=root;
	for(int i=0,index;s[i];i++) {
		for(;p->next[index=s[i]-‘a‘]==NULL&&p!=root;p=p->fail);
		p=p->next[index]==NULL?root:p->next[index];
		for(a tp=p;tp!=root&&tp->count!=-1;tp=tp->fail)
			cnt+=tp->count,tp->count=-1;
	}
	return cnt;
}
int main() {
	int n,q;
	scanf("%d",&q);
	while(q--) {
		root=new node;
		scanf("%d",&n);
		while(n--) {
			scanf("%s",key);
			insert(key,root);
		}
		Build_AC(root);
		scanf("%s",s);
		printf("%d\n",query(root));
	}
	return 0;
}

  

hdu 2222 Keywords Search

标签:fail   sys   modern   bottom   each   engine   printf   inpu   int   

原文地址:http://www.cnblogs.com/NuclearSubmarines/p/6851913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!