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<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<queue>
#include<math.h>
#include<vector>
#include<iostream>
using namespace std;
struct node{
node *next[26];
node *fail;
int sum;
node()
{
sum=0;
memset(next,NULL,sizeof(next));
fail=NULL;
}
}*q[500001];
char keyword[51];
char str[1000001];
int head,tail;
node *root;
void build(char *str)
{
node *p=root;
int i=0,id;
while(str[i])
{
id=str[i++]-'a';
if(p->next[id]==NULL)
p->next[id]=new node();
p=p->next[id];
}
p->sum++;
}
void build_aa()
{
int i;
root->fail=NULL;
q[head++]=root;
while(head!=tail)
{
node *temp=q[tail++];
node *p=NULL;
for(int i=0;i<26;i++)
{
if(temp->next[i])
{
if(temp==root) temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
temp->next[i]->fail=root;
}
q[head++]=temp->next[i];
}
}
}
}
int query()
{
int i=0,cnt=0,id,len=strlen(str);
node *p=root;
while(str[i])
{
id=str[i++]-'a';
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=(p->next[id]==NULL)?root:p->next[id];
node *temp=p;
while(temp!=root&&temp->sum!=-1)
{
cnt+=temp->sum;
temp->sum=-1;
temp=temp->fail;
}
}
return cnt;
}
int main()
{
int n,t;
scanf("%d",&t);
while(t--)
{
head=tail=0;
root=new node();
scanf("%d",&n);
getchar();
while(n--)
{
gets(keyword);
build(keyword);
}
build_aa();
scanf("%s",str);
printf("%d\n",query());
}
}
图像检索系统关键词匹配算法
本文介绍了一种图像检索系统中的关键词匹配算法实现。该算法通过构建前缀树(Trie)并使用AC自动机来高效地匹配用户输入的关键词与图像描述中的关键词。文章详细解释了算法的工作原理,包括如何构建前缀树、设置失败指针以及查询过程。
946

被折叠的 条评论
为什么被折叠?



