hdu 3065 病毒侵袭持续中(AC自动机)
这题我不释放trie的空间,结果MLE了一次。。。
#include <stdio.h>
#include <string.h>
#define MAXKIND 129
#define MAXN 1005
#define MAXLEN1 55
#define MAXLEN 2000005
#define MAXQSIZE 500005
typedef struct TNode
{
TNode()
{
id=-1;
fail=NULL;
memset(next,0,sizeof(next));
}
int id;
TNode *fail;
TNode *next[MAXKIND];
}*Trie;
void insert(Trie p,char *key,int idx)
{
while(*key)
{
int i=*key;
if(!p->next[i]) p->next[i]=new TNode;
p=p->next[i];
key++;
}
p->id=idx;
}
TNode *que[MAXQSIZE];
void build_ac(Trie root)
{
root->fail=NULL;
int front=-1,rear=-1;
que[++rear]=root;
TNode *out;
while(front<rear)
{
out=que[++front];
for(int i=0;i<MAXKIND;i++)
{
if(out->next[i])
{
que[++rear]=out->next[i];
if(out==root) out->next[i]->fail=root;
else
{
TNode *tmp=out->fail;
while(tmp)
{
if(tmp->next[i])
{
out->next[i]->fail=tmp->next[i];
break;
}
tmp=tmp->fail;
}
if(!tmp) out->next[i]->fail=root;
}
}
}
}
}
void search(Trie root,char *text,int *ha)
{
int i;
TNode *p=root;
while(*text)
{
i=*text;
while(!p->next[i] && p!=root) p=p->fail;
p=p->next[i];
if(!p) p=root;
TNode *tmp=p;
while(tmp->id != -1 && tmp != root)
{
ha[tmp->id]++;
tmp=tmp->fail;
}
text++;
}
}
void destroy(Trie &root)
{
if(!root) return;
for(int i=0;i<MAXKIND;i++) destroy(root->next[i]);
delete root;
}
char in[MAXN][MAXLEN1],str[MAXLEN];
int hash[MAXN];
int main()
{
#ifndef ONLINE_JUDGE
freopen("tdata.txt","r",stdin);
#endif
int i,n;
while(scanf("%d",&n)!=EOF)
{
Trie tree=new TNode;
for(i=1;i<=n;i++)
{
scanf("%s",in[i]);
insert(tree,in[i],i);
}
build_ac(tree);
scanf("%s",str);
memset(hash,0,sizeof(hash));
search(tree,str,hash);
for(i=1;i<=n;i++)
if(hash[i]) printf("%s: %d\n",in[i],hash[i]);
destroy(tree);
}
return 0;
}
浙公网安备 33010602011771号