#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
//DFA 求字符串最多匹配多少字符串
const int maxn=2000000;
struct Node
{
int num;//出现次数
int flag;//判断是否已经计算过
Node *next[27];//后继指针
Node* fail;//失败指针
/*指向树中出现过的S的最长的后缀,换句话说就是在前缀集中出现的最长的S的后缀.*/
};
//字典树
Node temp[maxn];
int tp;
//.........
int n;//字符串个数
Node *root;//头指针
void reset(Node* rot)
{
rot->num=0,rot->flag=0;
for(int i=0;i<27;i++) rot->next[i]=NULL;
rot->fail=root;//important
if(rot==root) rot->fail=NULL;//important
}
//初始化
void init()
{
tp=0;
root=&temp[tp++];
reset(root);
}
//插入字典树
void insert(char *word)
{
Node *p=root;
for(int i=0;word[i];i++)
{
int x=word[i]-'a';
if(p->next[x]==NULL)
{
p->next[x]=&temp[tp++];
reset(p->next[x]);
}
p=p->next[x];
}
p->num++;
}
//构造失败指针
Node *que[maxn];
int front,rear;
void DFA()
{
Node* p=root;
front=rear=0;
que[rear++]=p;
while(front<rear)
{
Node* t=que[front++];
for(int i=0;i<26;i++)
{
Node* cnt=t->next[i];
if(cnt!=NULL)
{
Node* fath=t->fail;
while(fath!=NULL&&fath->next[i]==NULL)
{
fath=fath->fail;
}
if(fath!=NULL)
{
cnt->fail=fath->next[i];
}
else
{
cnt->fail=p;//important
}
que[rear++]=cnt;
}
}
}
}
//查看str最多匹配多少字符串
int find(char* str)
{
Node* p=root;
Node* fath;
Node* cnt;
int ans=0;//结果
for(int i=0;str[i];i++)
{
int x=str[i]-'a';
cnt=p->next[x];
if(cnt!=NULL)
{
for(fath=cnt;fath!=NULL&&!fath->flag;fath=fath->fail)
{
if(fath->num)
{
ans+=fath->num;
fath->num=0;
}
fath->flag=1;
}
p=cnt;
}
else
{
fath=p->fail;
while(fath!=NULL&&fath->next[x]==NULL)
{
fath=fath->fail;
}
if(fath!=NULL)
{
cnt=fath->next[x];
for(fath=cnt;fath!=NULL&&!fath->flag;fath=fath->fail)
{
if(fath->num)
{
ans+=fath->num;
fath->num=0;
}
fath->flag=1;
}
p=cnt;
}
else
{
p=root;
}
}
}
return ans;
}
char str[1000005];
int main()
{
int ci;scanf("%d",&ci);
while(ci--)
{
scanf("%d",&n);
init();//初始化
for(int i=0;i<n;i++)
{
scanf("%s",str);
insert(str);//在字典树上插入字符串
}
DFA();//构造失败指针
scanf("%s",str);
printf("%d/n",find(str));
}
return 0;
}
本文介绍了一种利用DFA算法和字典树结构来高效查找一个字符串在多个字符串中最多能匹配到多少个字符串的方法。通过构建字典树并为每个节点设置失败指针,可以快速地进行字符串匹配。
437

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



