hdu 3695 ac自动机

n个子串,一个母串,问有多少个子串在母串中出现,包括被反转的子串。

只要把母串正着反着各自匹配一遍就行。

同样用的hdu 2222的模版


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node{
	int num;
	node *next[26],*fail;
	node(){
		num=0;
		fail=NULL;
		for(int i=0;i<26;i++)
			next[i]=NULL;
	}
}*q[6000010];
char ss[5555555],s[5555555],S[5555555];
void insert(char s[],node *root){
	int len=strlen(s);
	node *p=root;
	for(int i=0;i<len;i++){
		if(p->next[s[i]-'A']==NULL)
			p->next[s[i]-'A']=new node();
		p=p->next[s[i]-'A'];
	}
	p->num++;
}
void acmove(node *root){
	int head=0,tail=1;
	root->fail=NULL;
	q[0]=root;
	while(head!=tail){
		node *now=q[head++];
		node *p=NULL;
		for(int i=0;i<26;i++){
			if(now->next[i]!=NULL){
				if(now==root) now->next[i]->fail=root;
				else{
					p=now->fail;
					while(p!=NULL){
						if(p->next[i]!=NULL){
							now->next[i]->fail=p->next[i];
							break;
						}
						p=p->fail;
					}
					if(p==NULL)
						now->next[i]->fail=root;
				}
				q[tail++]=now->next[i];
			}
		}
	}
}
int find(node *root){
	int i=0,numb=0,len=strlen(ss);
	node *p=root;
	while(ss[i]){
		while(p->next[ss[i]-'A']==NULL&&p!=root)
			p=p->fail;
		p=p->next[ss[i]-'A'];
		p=(p==NULL)?root:p;
		node *now=p;
		while(now!=root&&now->num!=0){
			numb+=now->num;
			now->num=0;
			now=now->fail;
		}
		i++;
	}
	return numb;
}
int main(){
	int cas,n;
	node *root;
	scanf("%d",&cas);
	while(cas--){
		int N;
		root=NULL;
		root=new node();
		scanf("%d",&N);
		for(int i=0;i<N;i++){
			scanf("%s",s);
			insert(s,root);
		}
		acmove(root);
		int j=0;char c;
		getchar();  
		while(c=getchar(),c!='\n')  
		{  
			if(c=='[')  
			{  
				scanf("%d",&n);  
				c=getchar();  
				for(int i=0;i<n;i++)  
					ss[j++]=c;  
				getchar();  
			}  
			else ss[j++]=c;  
		}  
		ss[j]='\0';  
		int w=find(root);
		reverse(ss,ss+strlen(ss));
		w+=find(root);
		printf("%d\n",w);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值