HDU 2896 AC自动机

AC自动机模板

code:
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 60010;
int ans = 0;
char w[205], s[10010];
struct AC_Auto{
	int ch[N][128], f[N], val[N], sz;
	vector<int> word;/**存模式串下标*/
	AC_Auto(){
		memset(ch, 0, sizeof ch);
		memset(f, 0, sizeof f);
		memset(val, 0, sizeof val);
		sz = 1;
	}
	void insert(char *t, int id){
		int u = 0;
		for(int i = 0; t[i]; ++i){
			int c = (int)t[i];
			if(!ch[u][c]) ch[u][c] = sz++;
			u = ch[u][c];
		}
		val[u] = id;
	}
	void getFail(){
		queue<int>q;
		q.push(0);
		while(!q.empty()){
			int t = q.front();
			q.pop();
			for(int c = 0; c < 128; ++c){
				if(ch[t][c]){
					int u = ch[t][c], v = f[t];
					q.push(u);
					while(v && !ch[v][c]) v = f[v];
					f[u] = t ? ch[v][c] : 0;
				}
			}
		}
	}
	void query(char *t, int cas){
		int u = 0;
		for(int i = 0; t[i]; ++i){
			int c = (int)t[i];
			while(u && !ch[u][c]) u = f[u];
			u = ch[u][c];
			int tmp = u;
			while(tmp){/**while实现last数组*/
                if(val[tmp]) word.push_back(val[tmp]);
                tmp = f[tmp];
			}
		}
		if(word.size()) {
                ++ans;
                sort(word.begin(), word.end());
                cout << "web " << cas << ":";
                    for(int i = 0; i < word.size(); ++i) cout << " " << word[i];
                cout << endl;
                word.clear();
            }
	}
}ac;
int main(){

	int n, m;
	cin >> n;
	for(int i = 1; i <= n; ++i){
		cin >> w;
		ac.insert(w, i);
	}
	ac.getFail();
	cin >> m;
	for(int cas = 1; cas <= m; ++cas){
		cin >> s;
		ac.query(s, cas);
	}
	cout << "total: " << ans << endl;
	return 0;
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值