#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxn=5000100;
char str[2000050],key[55];
int allnum,vis[502];
vector<int>v[1001]; //用来标记每个网站的个数,
struct node
{
node *fail;
node *next[128];
int count,k; //记录单词结尾,判断是第几个单词。
node()
{
fail=NULL; //构造函数
count=0;k=0;
memset(next,NULL,sizeof(next));
}
};
node *root,*q[maxn];
int head,tail;
void InSert(char *str,int k)
{
int i=0;
node *p=root;
while(str[i])
{
int id=str[i];
if(p->next[id]==NULL) p->next[id]=new node(); //试了试和malloc时间差不多,用new更方便些,写的少。
p=p->next[id];
i++;
}
p->count++;
p->k=k;
}
void Build_ac_Bfs() //处理失败指针
{
q[tail++]=root;
while(head!=tail)
{
node *p=q[head++];
node *tmp=NULL;
for(int i=0;i<=127;i++)
{
if(p->next[i]==NULL) continue;
if(p==root) p->next[i]->fail=root;
else
{
tmp=p->fail;
while(tmp!=NULL)
{
if(tmp->next[i]!=NULL)
{
p->next[i]->fail=tmp->next[i];
break;
}
tmp=tmp->fail;
}
if(tmp==NULL) p->next[i]->fail=root;
}
q[tail++]=p->next[i];
}
}
}
void Query(int k,char *str) //查询
{
int id,len=strlen(str);
node *p=root;
for(int i=0;i<len;i++)
{
id=str[i];
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=p->next[id];
if(p==NULL) p=root;
node *tmp=p;
while(tmp!=root)
{
if(tmp->count>0&&vis[tmp->k]==0)
{ v[k].push_back(tmp->k);vis[tmp->k]=1; }
tmp=tmp->fail;
}
}
}
void Del(node *p)
{
for(int i=0;i<26;i++)
if(p->next[i]!=NULL)
Del(p->next[i]);
delete p;
}
void dis(int m)
{
allnum=0;
for(int i=1;i<=m;i++)
if(v[i].size()!=0)
{
allnum++;
sort(v[i].begin(),v[i].end());
printf("web %d:",i);
for(int j=0;j<v[i].size();j++)
printf(" %d",v[i][j]);
printf("\n");
}
printf("total: %d\n",allnum);
}
int main()
{
//freopen("Input.txt","r",stdin);
int n,m;
while(~scanf("%d",&n))
{
head=tail=0;
root=new node();
for(int i=0;i<1001;i++) v[i].clear();
getchar();
for(int i=1;i<=n;i++)
{
gets(key);
InSert(key,i);
}
Build_ac_Bfs();
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%s",str);
memset(vis,0,sizeof(vis));
Query(i,str);
}
dis(m);
Del(root);
}
return 0;
}
hdu2896ac自动机
最新推荐文章于 2020-07-27 19:43:52 发布
319

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



