HDU 2222 Keywords Search

比較裸的AC自動機。

借鑑:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef __int64 int64;
typedef long long ll;
#define M 500005
#define N 1000005
#define max_inf 0x7f7f7f7f
#define min_inf 0x80808080
const int  mod = 1e6;

struct node
{
	node *fail;
	node *next[26];
	int cout;
	node()
	{
		fail = NULL;
		memset(next , NULL , sizeof next);
		cout = 0;
	}
}*q[M];
char str[N];
int n;

void Insert(char *str , node *rt)
{
	int i = 0;
	node *p = rt;
	while (str[i])
	{
		int inx = str[i]-'a';
		if (!p->next[inx])p->next[inx] = new node;
		p = p->next[inx];
		i++;
	}
	p->cout++;
}

void Build(node *rt)
{
	rt->fail = NULL;
	int head , tail;
	head = tail = 0;
	q[tail++] = rt;
	while (head < tail)
	{
		int i;
		node *p = q[head++];
		for (i = 0 ; i < 26 ; i++)
		{
			if (!p->next[i])continue;
			if (p == rt)p->next[i]->fail = rt;
			else
			{
				node *temp = p->fail;
				while (temp)
				{
					if (temp->next[i])
					{
						p->next[i]->fail = temp->next[i];
						break;
					}
					temp = temp->fail;
				}
				if (!temp)p->next[i]->fail = rt;
			}
			q[tail++] = p->next[i];
		}
	}
}

void Solve(node *rt)
{
	int i = 0 , ans = 0;
	node *p = rt;
	while (str[i])
	{
		int inx = str[i]-'a';
		while (!p->next[inx] && p != rt)p = p->fail;
		p = p->next[inx];
		if (!p)p = rt;
		node *temp = p;
		while (temp != rt)
		{
			ans += temp->cout;
			temp->cout = 0;
			temp = temp->fail;
		}
		i++;
	}
	printf("%d\n",ans);
}

int main()
{
	int t;
	scanf("%d",&t);
	while (t--)
	{
		char keyword[55];
		node *rt = new node;
		scanf("%d",&n);
		while (n--)
		{
			scanf("%s",keyword);
			Insert(keyword,rt);
		}
		Build(rt);
		scanf("%s",str);
		Solve(rt);
	}
}


 

發佈了98 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章