AC自己主动机模板

AC自己主动机模板……


/*
 *	AC自己主动机模板
 *		用法:
 *			1、init() : 初始化函数
 *			2、insert(str) : 插入字符串函数
 *			3、build() : 构建ac自己主动机
 *			4、query(str) : 返回出现的字符串个数
 *
 *		使用需注意事项:
 *			1、注意输入的字符的范围,需对Next和其二维大小及相关參数进行更改
 *			2、注意Next、Fail和End数组的大小,防止超内存过数组越界
 *			3、依据实际情况对模板中“ buf[i] - 'a' ” 进行更改,否则可能会数组越界
 *		此模板默认相关设置:
 *			1、短字符串总长度不超过500000
 *			2、输入字符串的内容仅仅由小写字母a~z构成
 *			3、query()函数仅仅统计匹配的个数
 *				PS:上述都需依据须要自己更改。!。
 */
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;

int Next[500010][26], Fail[500010], End[500010];
int root, L;
int newnode() {
	for (int i = 0; i < 26; i++)
		Next[L][i] = -1;
	End[L++] = 0;
	return L - 1;
}
void init() {
	L = 0;
	root = newnode();
}
void insert(char buf[]) {
	int len = strlen(buf);
	int now = root;
	for (int i = 0; i < len; i++) {
		if (Next[now][buf[i] - 'a'] == -1)
			Next[now][buf[i] - 'a'] = newnode();
		now = Next[now][buf[i] - 'a'];
	}
	End[now]++;
}
void build() {
	queue<int>Q;
	Fail[root] = root;
	for (int i = 0; i < 26; i++) {
		if (Next[root][i] == -1)
			Next[root][i] = root;
		else {
			Fail[Next[root][i]] = root;
			Q.push(Next[root][i]);
		}
	}
	while ( !Q.empty() ) {
		int now = Q.front();
		Q.pop();
		for (int i = 0; i < 26; i++) {
			if (Next[now][i] == -1)
				Next[now][i] = Next[Fail[now]][i];
			else {
				Fail[Next[now][i]] = Next[Fail[now]][i];
				Q.push(Next[now][i]);
			}
		}
	}
}
int query(char buf[]) {
	int len = strlen(buf);
	int now = root;
	int res = 0;
	for (int i = 0; i < len; i++) {
		now = Next[now][buf[i] - 'a'];
		int temp = now;
		while ( temp != root ) {
			res += End[temp];
			End[temp] = 0;
			temp = Fail[temp];
		}
	}
	return res;
}


int main() {
	freopen("in.in", "r", stdin);
	freopen("out.out", "w", stdout);
	return 0;
}


原文地址:https://www.cnblogs.com/zhchoutai/p/7073732.html