您的位置:首页 > 其它

HDU 2222

2017-08-24 10:34 141 查看

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2222

题解:

AC自动
4000
机模板题

代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn1=1e6+10;
const int maxn2=1e4+10;
char keyword[maxn2];
char s[maxn1];

struct node
{
int cnt;
node  *next[26],*fail;
node()
{
cnt=0;
fail=NULL;
for(int i=0;i<26;i++)
next[i]=0;
}
}*root;

//构建字典树
void insert(char *s,node *p)
{
int i=0,k;
while(s[i])
{
k=s[i++]-'a';
if(p->next[k]==NULL)
p->next[k]=new node();
p=p->next[k];
}
p->cnt++;
}

node *q[maxn1];

//构建fail指针
void build(node *root)
{
int head=0,tail=1;
q[head]=root;
node *temp,*p;
while(head<tail)
{
temp=q[head++];
//        查找当前节点的子节点
for(int i=0;i<26;i++)
{
if(temp->next[i])
{
if(temp==root)
//                    当这个子节点是ROOT的子节点时,它的fail指针就是ROOT
temp->next[i]->fail=root;
else
{
p=temp->fail;
//                     指向这个子节点的父亲节点fail指针
while(p)
{
//                            查找这个子节点的父亲节点fail指针的节点的子节点,看看有没有出现过这个子节点
if(p->next[i])
//                            有的话,直接指过去
{
temp->next[i]->fail=p->next[i];
break;
}
//                        没有的话,就继续找
p=p->fail;
}
if(!p)
//                        没有找到,那么就把这个节点的fail指针指向ROOT
temp->next[i]->fail=root;
}
q[tail++]=temp->next[i];
}
}
}
}

//查询
int query(char *s,node *root)
{
int ans=0,len=strlen(s),k;
node *p=root;
for(int i=0;i<len;i++)
{
k=s[i]-'a';
//        如果找不到,就进行fail指针去寻找
while(!p->next[k]&&p!=root)
p=p->fail;
p=p->next[k];
if(!p)
p=root;
node *temp=p;
while(temp!=root&&temp->cnt!=-1)
{
ans+=temp->cnt;
//            如果匹配了,那么就加上这个点上的CNT值
temp->cnt=-1;
//            将找过的标记一下
temp=temp->fail;
}
}
return ans;
}

//多次进行,初始化
void del(node *root)
{
if(root==NULL)
return;
for(int i=0;i<26;i++)
del(root->next[i]);
delete (root);
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
root = new node();
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",keyword);
insert(keyword,root);
}
build(root);
scanf("%s",s);
printf("%d\n",query(s,root));
del(root);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: