题目链接:hdu 2896 病毒侵袭
简单的变形,说来惭愧,弄了我一个下午,始终在Tl和WA和爆内存间徘徊
首先在建立字典树时,要稍微修改,每个单词的末尾记录为该单词的序号,以便在输出在主串中找到哪些单词
第二点变化之处,在询问时,每当找到单词,将它的尾部存的序号存入一个数组进行保存,还要统计出现单词的个数,对后面判断是否有单词出现提供依据
说说我被坑的地方;
第一:中间不要用fill函数进行初始化,要用memset,否则TL到死
第二:搞错存放单词序号的数组大小了,一直wa
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define maxn 2222222
using namespace std;
int head,tail;
bool num[555];//若病毒在网站内出现,则下标对应的值为真
char s[maxn];
struct node
{
node *fail;
node *next[98];//建立98叉树,因为前面的31个字符不可见
int count;
node()
{
count=0;
fail=NULL;
memset(next,0,sizeof(next));
}
}*q[maxn];
node *root;
void insert(char s[],int ID)
{
node *p=root;
int len =strlen(s);
for(int i=0;i<len;i++)
{
int id = s[i]-31;//ascii减31
if(p->next[id]==NULL) p->next[id]=new node();
p=p->next[id];
}
p->count=ID;//病毒末尾记录该病毒的标号
}
void build_ac()
{
node *p,*temp=NULL;
q[tail++]=root;
while(head!=tail)
{
p=q[head++];
for(int i=0;i<98;i++)
{
if(p->next[i])
{
if(p==root) p->next[i]->fail=root;
else
{
temp =p->fail;
while(temp!=NULL)
{
if(temp->next[i])
{
p->next[i]->fail=temp->next[i];
break;
}
temp=temp->fail;
}
if(temp==NULL) p->next[i]->fail=root;
}
q[tail++]=p->next[i];
}
}
}
}
int query(char s[])
{
node *p=root;
int len =strlen(s);
int res = 0;
for(int i=0;i<len;i++)
{
int id = s[i]-31;
while(p->next[id]==NULL&&p!=root) p=p->fail;
p=p->next[id];
if(p==NULL) p=root;
node *temp = p;
while(temp!=root&&!num[temp->count])
{
if(temp->count) res++;
num[temp->count]=temp->count;//对应字符做上标记
temp=temp->fail;
}
}
return res;
}
void Free(node *p)
{
for(int i=0;i<98;i++)
if(p->next[i]) Free(p->next[i]);
free(p);
}
int main()
{
int t,n,m;
while(~scanf("%d",&n))
{
root = new node();
for(int i=1;i<=n;i++)
{
scanf("%s",s);
insert(s,i);
}
build_ac();
int sum=0;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
memset(num,0,sizeof(num));//大坑点,不能用fill函数初始化。否则TL到死
head=tail=0;
scanf("%s",s);
int res=query(s);
if(res)
{
printf("web %d:",i);
for(int j=0;j<555;j++)//输出出现单词的序号
if(num[j]) printf(" %d",j);
printf("\n");
sum++;
}
}
printf("total: %d\n",sum);
Free(root);//释放内存
}
return 0;
}