HDU 2896 (AC自动机)

HDU 2896 病毒侵袭

Problem : 给n个模式串,m个目标串,询问每个目标串含有哪些模式串。
**Solution : **将模式串建立AC自动机,对于每个目标串,开一个数组表示每个模式串是否匹配,在AC自动机上跑一遍即可。

#include <iostream>
#include <string>
#include <queue>

using namespace std;
const int N = 100008;

struct AC_Automan
{
	int next[N][128];
	int fail[N];
	int val[N];
	int tot, root;
	int used[1000];
	int newnode()
	{
		for (int i = 0; i < 127; ++i) next[tot][i] = -1;
		fail[tot] = val[tot] = -1;
		return tot++;
	}
	void clear()
	{
		tot = 0;
		root = newnode();
	}
	void insert(const string &s, int id)
	{
		int p = root;
		for (int len = s.length(), i = 0; i < len; ++i)
		{
			if (next[p][s[i]] == -1) next[p][s[i]] = newnode();
			p = next[p][s[i]];
		}
		val[p] = id;
	}
	void build()
	{
		queue <int> Q;
		Q.push(root);
		while (!Q.empty())
		{
			int p = Q.front(); Q.pop();
			for (int i = 0; i < 127; ++i)
			{
				if (~next[p][i])
				{
					if (p == root) fail[next[p][i]] = root;
					else fail[next[p][i]] = next[fail[p]][i];
					Q.push(next[p][i]);
				}
				else
				{
					if (p == root) next[p][i] = root;
					else next[p][i] = next[fail[p]][i];
				}
			}
		}
	}
	int solve(const string &t, int id)
	{
		for (int i = 1; i <= 500; ++i) used[i] = 0;
		int p = root;
		for (int i = 0, len = t.length(); i < len; ++i)
		{
			p = next[p][t[i]];
			for (int temp = p; temp != root; temp = fail[temp])
			{
				if (~val[temp]) used[val[temp]] = 1;
			}
		}
		int sum = 0;
		for (int i = 1; i <= 500; ++i)
		{
			if (used[i]) sum++;
		}
		if (sum == 0) return 0;
		cout << "web " << id << ": ";
		for (int i = 1, num = 0; i <= 500; ++i)
		{
			if (used[i]) 
			{
				num++;
				cout << i;
				if (num == sum) cout << endl; else cout << " ";
			}
		}
		return 1;
	}
}ac;

int main()
{
	cin.sync_with_stdio(0);
	int n; 
	while (cin >> n)
	{
		ac.clear();
		for (char ch = cin.get(); ch != '\n'; ch = cin.get());
		for (int i = 1; i <= n; ++i)
		{
			string s; getline(cin, s);
			ac.insert(s, i);	
		}
		ac.build();
		int m; cin >> m;
		for (char ch = cin.get(); ch != '\n'; ch = cin.get());
		int ans = 0;
		for (int i = 1; i <= m; ++i)
		{
			string t; getline(cin, t);
			if (ac.solve(t, i)) ans++;
		}
		cout << "total: " << ans << endl;
	}
}  
posted @ 2017-07-16 18:47  rpSebastian  阅读(208)  评论(0编辑  收藏  举报