HDU 2896 病毒入侵 AC自动机

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

#define NUM 128
#define ST  0
#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];

bool output[ 501 ];
int head, tail;
char text[5000001]; //文本
void insert( char *str, Node *root,int j )
{
	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 = j;  //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 )
		{
			output[temp->count] = true;
			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[201];

int main()
{
	//freopen( "1.txt","r",stdin );
	scanf( "%d",&t );
	root = new Node();
	for( int i = 1;i <= t;i++ )
	{
		scanf( "%s",str );
		insert( str,root,i );
	}
	Build_AC( root );

	scanf( "%d",&n );

	int result = 0;
	for( int i = 1;i <= n;i++ )
	{
		scanf( "%s",text );

		memset( output,false,sizeof(output ) );
		query( root );

		int s[10], m = 0;
		for( int j = 1;j<= t;j++ ) 
		{
			if( output[j] ) s[m++] = j;
		}

		if( m )
		{
			printf( "web %d:",i );
			for( int j = 0;j < m;j++ ) printf( " %d",s[j] ); printf( "\n" );
			result++;
		}
	}
	printf( "total: %d\n",result );


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值