【模板】AC自动机

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<vector>
using namespace std;
typedef struct _node {
	vector<int> exist;
	_node* fail;
	_node* child[26];
}node;
//const char* p[] = { "he","she","hers","his" };
vector<string>p;
const char* T = "ahishers";
int trie[100010][26];
queue<node*>q;
void insert(node* &root, string s)
{
	node* p = root;
	for (int i = 0; i < s.size(); i++)
	{
		int c = s[i] - 'a';
		if (p->child[c] == NULL)
		{
			node* k = new node;
			for (int j = 0; j < 26; j++) k->child[j] = NULL;
			k->exist.clear(); k->fail = NULL;
			p->child[c] = k;
		}
		p = p->child[c];
	}
	p->exist.push_back(s.size());
}
void build(node* &root)
{
	node* fafail;
	int n = p.size();
	for (int i = 0; i < n; i++)
	{
		insert(root, p[i]);
	}
	for (int i = 0; i < 26; i++)
	{
		if (root->child[i])
		{
			q.push(root->child[i]);
			root->child[i]->fail = root;
		}
	}
	while (!q.empty())
	{
		node* x = q.front();
		q.pop();
		for (int i = 0; i < 26; i++)
		{
			node* y;
			if (x->child[i])
			{
				y = x->child[i];
				fafail = x->fail;
				while (fafail&&fafail->child[i] == NULL)
				{
					fafail = fafail->fail;
				}
				if (fafail == NULL)
				{
					y->fail = root;
				}
				else
				{
					y->fail = fafail->child[i];
					if (y->fail->exist.size())
					{
						for (int j = 0; j < y->fail->exist.size(); j++)
						{
							y->exist.push_back(y->fail->exist[j]);
						}
					}
				}
				q.push(y);
			}
		}
	}
}
void query(node* &root)
{
	node* tmp = root;
	for (int i = 0; i < strlen(T); i++)
	{
		int c = T[i] - 'a';
		while (tmp->child[c] == NULL && tmp->fail) tmp = tmp->fail;
		if (tmp->child[c]) tmp = tmp->child[c];
		else continue;
		if (tmp->exist.size())
		{
			for (int j = 0; j < tmp->exist.size(); j++)
			{
				int len = tmp->exist[j];
				printf("查找位置=%d,长度=%d", i - len + 1, len);
			}
		}
	}
}
int main()
{
	node* root = new node;
	for (int i = 0; i < 26; i++) root->child[i] = NULL;
	root->fail = NULL;
	root->exist.clear();
	p.push_back("he");
	p.push_back("she");
	p.push_back("hers");
	p.push_back("his");
	build(root);
	query(root);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值