HDU-2222-Aho-Corasick--自动机

模板题目

理解了AC自动机之后感觉这真是一个奇妙的东西▼o・ェ・o▼

参考  http://blog.csdn.net/zxy_snow/article/details/6709255

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int SIGMA_SIZE = 26;
struct node
{
	node * ch[SIGMA_SIZE];
	node * back;
	int cnt;
	node()
	{
		back=NULL;
		cnt=0;
		for(int i=0;i<SIGMA_SIZE;i++)
			ch[i]=NULL;
	}
};
node * root;
int idx(const char c)
{
	return c-'a';
}
void insert(const char *s)
{
	int c,len =strlen(s);
	node *u=root;
	for(int i=0;i<len;i++)
	{
		c=idx(s[i]);
		if(u->ch[c]==NULL)
		{
			u->ch[c]=new node();
		}
		u=u->ch[c];
	}
	u->cnt++;
}
void getFail()
{
	queue<node *> q;
	q.push(root);
	node *now,*p;
	while(!q.empty())
	{
		now=q.front();q.pop();
		for(int i=0;i<SIGMA_SIZE;i++)
		{
			if(now->ch[i])
			{
				p=now->back;
				while(p)
				{
					if(p->ch[i])
					{
						now->ch[i]->back=p->ch[i];
						break;
					}
					p=p->back;
				}
				if(p==NULL)
					now->ch[i]->back = root;
				q.push(now->ch[i]);
			}
		}
	}
}
int ans =0 ;
void find(const char *t)
{
	ans=0;
	node * u=root;
	int len = strlen(t);
	for(int i=0;i<len;i++)
	{
		int c = idx(t[i]);
		while(u->ch[c]==NULL&&u!=root)
		{
			u=u->back;
		}
		u=u->ch[c]==NULL?root:u->ch[c];

		node * temp = u;
		while(temp!=root&&temp->cnt>0)
		{
			ans+=temp->cnt;
			temp->cnt=-1;
			temp = temp->back;
		}
	}
}

char t[1000090];


int main()
{
	freopen("data.in","r",stdin);
	char s[100];
	int n,T;
	scanf("%d",&T);
	while(T--)
	{
		root=new node();
		scanf("%d",&n);
		while(n--)
		{
			scanf("%s",s);
			insert(s);
		}
		getFail();
		scanf("%s",t);
		find(t);
		printf("%d\n", ans);
	}
	return 0;
}

板子留着


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值