1. 程式人生 > >AC自己主動機模板

AC自己主動機模板

自己 可能 sin code [] stdin 插入字符 strlen pen

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;
}


AC自己主動機模板