利用trie树和KMP算法:就是在 Trie 上进行 KMP 匹配。
题意:给你n个单词和一条字符串,问你在这个字符串中,包含几个单词。
思路:这是一条多串匹配的题目,AC自动机
//
#include<iostream>
#include<string.h>
#include<queue>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
int count;//判断是不是单词的最后一个节点
struct node *fail;//失败指针
struct node *next[26];//Tire每个节点的儿子节点
node()
{
fail=NULL;
count=0;
memset(next,NULL,sizeof(next));
}
};
char keyword[10010];
char str[1000010];
void buildTree(char *word,struct node *root)
{
struct node *p=root;
int i=0,index;
int len=strlen(word);
for(int i=0; i<len; i++)
{
index=word[i]-'a';
if(p->next[index]==NULL)
p->next[index]=new node();
p=p->next[index];
}
p->count++;
}
void BFS(struct node* root)
{
queue<struct node*> q;
struct node *temp,*p;
root->fail=NULL;
q.push(root);
while(!q.empty())
{
temp=q.front();
q.pop();
for(int i=0; i<26; i++)
{
if(temp->next[i]!=NULL)
{
if(temp==root) temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
temp->next[i]->fail=root;
}
q.push(temp->next[i]);
}
}
}
}
int find(struct node *root)
{
int cnt=0,index,len=strlen(str);
struct node *p=root;
for(int i=0;i<len;i++)
{
index=str[i]-'a';
while(p->next[index]==NULL&&p!=root)//最长后缀
p=p->fail;
p=(p->next[index]==NULL?root : p->next[index]);
struct node *temp=p;
while(temp!=root&&temp->count!=-1)
{
cnt+=temp->count;
temp->count=-1;
temp=temp->fail;
}
}
return cnt;
}
int main()
{
int T;
int test;
struct node *root=NULL;
scanf("%d",&T);
while(T--)
{
root=new node();
scanf("%d",&test);
for(int i=0; i<test; i++)
{
scanf("%s",keyword);
buildTree(keyword,root);
}
BFS(root);
scanf("%s",str);
int ans=find(root);
printf("%d\n",ans);
}
return 0;
}
/*
1
5
she
he
say
shr
her
her
*/