hdu 2222 Keywords Search
AC自动机模板。。。
#include <stdio.h>
#include <string.h>
#define MAXKLEN 55
#define MAXDLEN 1000005
#define MAXQSIZE 500005
typedef struct TNode
{
TNode()
{
count=0;
fail=NULL;
memset(next,NULL,sizeof(next));
}
int count;
TNode *fail;
TNode *next[26];
}*Trie;
TNode *que[MAXQSIZE];
void insert(Trie p,char *key)
{
int i;
while(*key)
{
i = *key - 'a';
if(!p->next[i]) p->next[i] = new TNode;
p = p->next[i];
key++;
}
p->count++;
}
void build_ac_automation(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<26;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;
}
}
}
}
}
int search(Trie root,char *pat)
{
int i,cnt=0;
TNode *p = root;
while(*pat)
{
i = *pat - 'a';
while(!p->next[i] && p != root) p=p->fail;
p = p->next[i];
if(!p) p = root;
TNode *tmp = p;
while(tmp->count!=-1 && tmp != root)
{
cnt+=tmp->count;
// printf("tmp->count=%d pat=%s\n",tmp->count,pat);
tmp->count = -1;
tmp = tmp->fail;
}
pat++;
// printf("pat=%s cnt=%d\n",pat,cnt);
}
return cnt;
}
inline void destroy(Trie &root)
{
if(!root) return;
for(int i=0;i<26;i++) destroy(root->next[i]);
delete root;
}
char description[MAXDLEN];
int main()
{
#ifndef ONLINE_JUDGE
freopen("tdata.txt","r",stdin);
#endif
int T,n;
char keys[MAXKLEN];
scanf("%d",&T);
while(T--)
{
Trie tree = new TNode;
scanf("%d",&n);
while(n--)
{
scanf("%s",keys);
insert(tree,keys);
}
build_ac_automation(tree);
// printf("build count\n");
scanf("%s",description);
printf("%d\n",search(tree,description));
// destroy(tree);
}
return 0;
}
浙公网安备 33010602011771号