HDU-2222 AC自动机

本文介绍了一种基于 AC 自动机实现的图像检索系统,该系统通过匹配关键词与图像描述来检索图片。文章详细展示了 AC 自动机的构建过程,包括初始化、添加关键词、构建失败指针及查询操作。此外,还提供了完整的 C++ 实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

板子

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5,M=1e6+6;
struct aho{
	int next[N][26],fail[N],ed[N],root,tot;
	queue<int>q;
	int newnode(){
		for(int i=0;i<26;++i)next[tot][i]=-1;
		ed[tot]=0;
		return tot++;
	}
	void init(){
		tot=0,root=newnode();
		while(!q.empty())q.pop();
	}
	void add(char s[]){
		int len=strlen(s),now=root;
		for(int i=0;i<len;++i){
			int ch=s[i]-'a';
			if(next[now][ch]==-1)next[now][ch]=newnode();
			now=next[now][ch];
		}
		++ed[now];
	}
	void build(){
		fail[root]=root;
		for(int i=0;i<26;++i)
			if(next[root][i]==-1)next[root][i]=root;
			else fail[next[root][i]]=root,q.push(next[root][i]);
		while(!q.empty()){
			int now=q.front();q.pop();
			for(int i=0;i<26;++i)
				if(next[now][i]==-1)next[now][i]=next[fail[now]][i];
				else fail[next[now][i]]=next[fail[now]][i],q.push(next[now][i]);
		}
	}
	int query(char s[]){
		int len=strlen(s),now=root,res=0;
		for(int i=0;i<len;++i){
			now=next[now][s[i]-'a'];
			int tmp=now;
			while(tmp!=root)res+=ed[tmp],ed[tmp]=0,tmp=fail[tmp];
		}
		return res;
	}
}ac;
char s[M];
int main(){
	int t;scanf("%d",&t);
	while(t--){
		int n;scanf("%d",&n);
		ac.init();
		while(n--)scanf("%s",s),ac.add(s);
		ac.build();
		scanf("%s",s);
		printf("%d\n",ac.query(s));
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值