您的位置:首页 > 其它

HDU 2222 Keywords Search

2012-02-22 07:30 274 查看
题意:这AC自动机还能再裸一点么...

Trie树+失配指针,不会的去网上找论文吧。

直接上代码:

View Code

#include<queue>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;

struct node
{
int num;
node *fail,*next[26];
void init()
{
num=0;
fail=NULL;
memset(next,NULL,sizeof(next));
}
}*root;
node T[500010];

int n,tot,ans;
char str[1000010];
queue<node*> q;

void Insert(char s[])
{
node *p=root;
for(int i=0;s[i];i++)
{
if (p->next[s[i]-'a']==NULL)
{
p->next[s[i]-'a']=T+ ++tot;
p->next[s[i]-'a']->init();
}
p=p->next[s[i]-'a'];
}
p->num++;
}
void clear(node *root)
{
root->num=0;
root->fail=NULL;
for (int i=0;i<26;i++)
if (root->next[i]!=NULL)
{
clear(root->next[i]);
root->next[i]=NULL;
}
}

void built()
{
root->fail=NULL;
q.push(root);
while (!q.empty())
{
node *u=q.front();
q.pop();
for (int i=0;i<26;i++)
{
node* temp=u->next[i],*p;
if (temp!=NULL)
{
for (p=u->fail;p;p=p->fail)
if (p->next[i]) {temp->fail=p->next[i];break;}
if (p==NULL) temp->fail=root;
q.push(temp);
}
}
}
}

void slove()
{
int index;
node *p=root;
for (int i=0;str[i];i++)
{
index=str[i]-'a';
while (!p->next[index] && p!=root) p=p->fail;
p=p->next[index];
if (p==NULL) p=root;
node *temp=p;
while (temp!=root && temp->num!=-1)
{
ans+=temp->num;
temp->num=-1;
temp=temp->fail;
}
}
}
int main()
{
freopen("1.in","r",stdin);
freopen("out","w",stdout);
int Case;
scanf("%d",&Case);
while (Case--)
{
tot=0;ans=0;
root=T+ ++tot;
root->init();
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%s",str),Insert(str);
built();
scanf("%s",str);
slove();
printf("%d\n",ans);
}
return 0;
}


这题也确实够2的,名字多V5...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: