hdu2222及易错数据(AC自动机)

RT.

#include <iostream>
#include <stdarg.h>

using namespace std;

const int kind=26;
struct node{
  node* fail;
  node* next[kind];
  int count;//是否为该单词的最后一个节点
  node(){
     fail=NULL;
	 count=0;
	 memset(next,NULL,sizeof(next));
  }
} *q[500001];//队列

char keyword[51];
char str[1000001];
int head,tail;//队列的头尾指针

void insert(char *str,node *root)//构造trie树
{  
   node *temp=root;
   int i=0;
   while(str[i])
   {
      if(temp->next[str[i]-'a']==NULL) temp->next[str[i]-'a']=new node();
	      temp=temp->next[str[i]-'a'];
      i++;
   }
   temp->count++;
}

void build_ac_automation(node *root)//构造fail指针
{
	q[0]=root;
	root->fail=NULL;
	head=0;tail=1;
	while(head!=tail)
	{   
	   for(int i=0;i<kind;i++)
	   {
		   if(q[head]->next[i]!=NULL)
		   {
			   q[tail++]=q[head]->next[i];
			    node* temp=q[head];
				while(temp->fail!=NULL)
				{
					if(temp->fail->next[i]!=NULL)
					{
						q[head]->next[i]->fail=temp->fail->next[i];
					    break;
					}
					temp=temp->fail;
				}
				if(temp->fail==NULL)
				   q[head]->next[i]->fail=root;
		   }
	   }
	  head++;
	}

}

int query(node* root)//查询过程
{
   int i=0, count=0,index,len=strlen(str); 
   node *temp=root;
   while(str[i])
   {
	    while(temp!=NULL&&temp->next[str[i]-'a']==NULL)
		    temp=temp->fail;
		if(temp!=NULL)
		{
			temp=temp->next[str[i]-'a'];
			node *temp2=temp;
			while(temp2->fail!=NULL)
			{
				if(temp2->count>=1)
				{
				   count+=temp2->count;
				   temp2->count=-1;
				}
				temp2=temp2->fail;
			}
		}
		else
		{
			temp=root;
		}
	    i++;
   }
   return count;
}



int main()
{
	int n;
	int g;
	scanf("%d",&g);
	for(int i=0;i<g;i++)
	{
		node *root=new node(); 
		scanf("%d",&n); 
		getchar(); 
		while(n--){ 
			gets(keyword); 
			insert(keyword,root); 
		} 
		build_ac_automation(root); 
		scanf("%s",str); 
		printf("%d\n",query(root));  
	}
  return 0;
}

/**
易错测试数据 
1 
h 
hhhhh 
结果是1,因为只有一个关键字h,而字符串中出现了4次h,但是算做重复,只计数一次 
2 
a 
a 
a 
结果是2,因为keywords中a 出现了两次 
 
 */


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值