hdu 2896 字典树解法

时间:2021-10-26 13:14:14
 #include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct Tree
{
Tree *next[];
bool isVirus;
int num;
};
Tree *root;
int all;
char temp[];
int temps[];
int n,m;
void insert(char temp[],int Num)
{
int len=strlen(temp);
Tree *the=root;
for(int i=; i<len; i++)
{
int temps=temp[i]-' ';
if(the->next[temps]==NULL)
{
Tree* ttemp=(Tree *)malloc(sizeof(Tree));
for(int j=; j<; j++)
ttemp->next[j]=NULL;
ttemp->isVirus=false;
if(i==len-)
{
ttemp->isVirus=true;
ttemp->num=Num;
}
the->next[temps]=ttemp;
}
else if(i==len-)
{
the->next[temps]->isVirus=true;
the->next[temps]->num=Num;
}
the=the->next[temps];
}
}
void search(int num)
{
int virusNum=;
int vir[];
int len=strlen(temp);
for(int i=; i<len; i++)
{
Tree* the=root;
for(int j=; i+j<len; j++)
{
int ttemp=(int)(temp[i+j]-' ');
if(the->next[ttemp]==NULL)break;
else if(the->next[ttemp]->isVirus)
{
bool ok=false;
for(int s=; s<virusNum; s++)
{
if(vir[s]==the->next[ttemp]->num)
ok=true;
}
if(!ok)
{
vir[virusNum++]=the->next[ttemp]->num;
i=i+j;
break;
}
else
the=the->next[ttemp];
}
else
the=the->next[ttemp];
}
if(virusNum==)break;
}
if(virusNum)
{
all++;
printf("web %d:",num);
sort(vir,vir+virusNum);
for(int i=; i<virusNum; i++)
printf(" %d",vir[i]);
printf("\n");
}
}
int main()
{
int virusNum;
int vir[];
root=(Tree *)malloc(sizeof(Tree));
for(int i=; i<; i++)
root->next[i]=NULL;
root->isVirus=false;
cin>>n;
for(int i=; i<=n; i++)
{
scanf("%s",temp);
insert(temp,i);
}
cin>>m;
for(int i=; i<=m; i++)
{
scanf("%s",temp);
search(i);
}
printf("total: %d\n",all);
return ;
}

本题很水,直接字典树可以a掉,不过听说是ac自动机模板题,有学ac自动机的想法,后面也许会贴上ac自动机的代码。