HDU 2222 Keywords Search AC自动机 可做模板

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#define NUM 26
#define ST  'a'
#define QMAX 500001
struct Node
{
	Node *fail;
	Node *nxt[NUM];

	int count; // 单词结束点+1
	Node()
	{
		fail = NULL;
		memset( nxt,0,sizeof(nxt) );
		count = 0;
	}
}*Q[QMAX];

int head, tail;
char text[5000001]; //文本
void insert( char *str, Node *root )
{
	int len = strlen( str );

	Node *temp = root;
	for( int i = 0;i < len;i++ )
	{
		int nxtp = str[i] - ST;
		if( !temp->nxt[ nxtp ] )
		{
			temp->nxt[ nxtp ] = new Node();
		}
		temp = temp->nxt[ nxtp ];
	}
	temp->count++;
}

void Build_AC( Node *root )
{
	root->fail = NULL;

	Q[ head++ ] = root;
	if( head == QMAX ) head = 0;
	while( head != tail )
	{
		Node *temp = Q[tail++];
		if( tail == QMAX ) tail = 0;
		Node *p = NULL;
		for( int i = 0;i < NUM;i++ )
		{
			if( temp->nxt[i] )
			{
				if( temp == root ) temp->nxt[i]->fail = root;
				else
				{
					p = temp->fail;
					while( p )
					{
						if( p->nxt[i] )
						{
							temp->nxt[i]->fail = p->nxt[i];
							break;
						}
						p = p->fail;
					}
					if( !p ) temp->nxt[i]->fail = root;
				}
				Q[head++] = temp->nxt[i];
				if( head == QMAX ) head = 0;
			}
		}
	}
}

int query( Node *root )
{
	int result = 0, len = strlen( text );
	
	Node *p = root;
	for( int i = 0;i < len;i++ )
	{
		int nxtp = text[i] - ST;

		while( !p->nxt[nxtp] && p != root ) p = p->fail;

		p = p->nxt[nxtp];
		if( !p ) p = root;

		Node *temp = p;
		while( temp != root && temp->count != 0 )
		{
			result += temp->count;
			temp->count = 0;
			temp = temp->fail;
		}

	}
	return result;
}
void Release( Node *root )
{
	for( int i = 0;i < NUM;i++ )
	{
		if( root->nxt[i] ) Release( root->nxt[i] );
	}
	delete root;
}

int t, n;
Node *root = NULL;
char str[51];

int main()
{
	scanf( "%d",&t );
	while( t-- )
	{
		head = tail = 0;
		root = new Node();
		scanf( "%d",&n );

		while( n-- )
		{
			scanf( "%s",str );
			insert( str,root );
		}
		Build_AC( root );

		scanf( "%s",text );

		printf( "%d\n", query( root ) );

		//Release( root );  //销空间能免就省吧
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值