您的位置:首页 > 其它

(模板)AC自动机

2014-10-13 23:09 309 查看
struct trie {
	int ch[mxnode][26], lst[mxnode], cnt[mxnode], f[mxnode], sz;
	int creat() {
		memset(ch[sz], -1, sizeof(ch[sz]));
		cnt[sz] = 0;
		return sz++;
	}
	void init() {
		sz = 0, creat();
	}
	void insert(char *s, int val) {
		int t = 0;
		for(int i = 0; s[i]; ++i) {
			int c = s[i] - 'a';
			if(!~ch[t][c]) ch[t][c] = creat();
			t = ch[t][c];
		}
		cnt[t] += val;
	}
	void build() {
		queue<int> q; f[0] = 0;
		for(int i = 0; i < 26; ++i) {
			int &v = ch[0][i];
			if(!~v) v = 0;
			else f[v] = 0, q.push(v);
		}
		while(!q.empty()) {
			int t = q.front(); q.pop();
			if(cnt[f[t]]) cnt[t] = 1; //注意要不要加这行
			for(int i = 0; i < 26; ++i) {
				int &v = ch[t][i];
				if(!~v) v = ch[f[t]][i];
				else {
					f[v] = ch[f[t]][i];
					lst[v] = cnt[f[v]]? f[v]: lst[f[v]];
					q.push(v);
				}
			}
		}
	}
	mat get_mat() { //构造一个状态转移矩阵
		mat ret(sz);
		for(int i = 0; i < sz; ++i) {
			for(int j = 0; j < 26; ++j) {
				int v = ch[i][j];
				if(cnt[v] == 0) ret.a[i][v]++;
			}
		}
		return ret;
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: