AC自动机 (Trie图优化)

#include
#include
#include
#include
#include
#define For(i,j,k) for (i=j;i<=k;i++)
using namespace std;

const int dmax=1010;

struct node{
	int count,flag;
	struct node *next[26],*fa,*fail;
	char s1[110];
	node(){
		fail=fa=NULL;
		count=flag=0;
		memset(next,0,sizeof(next));
		memset(s1,0,sizeof(s1));
	}
};
struct node *root,*h,*fa,*tmp,*temp;
struct node *q[dmax*dmax];
char p[dmax][dmax];
char s[dmax*dmax];

void insert(char *w){
	int i,k,n=strlen(w);
	h=root;
	For(i,0,n-1){
		k=w[i]-97;
		if (h->next[k]==NULL){
			tmp=new node;
			tmp->fa=h;
			h->next[k]=tmp;
		}
		h=h->next[k];
	}
	h->count=1;
	h->flag=0;
	strcpy(h->s1,w);
}
void create_fail(){
	int i,f=0,l=1;
	q[1]=root;
	while (fnext[i]==NULL)
				fa->next[i]=fa==root?root:fa->fail->next[i];
			else{
				fa->next[i]->fail=fa==root?root:fa->fail->next[i];
				q[++l]=fa->next[i];
			}
	}
}
void auto_search(char *s){
	int i,j,k,m,n=strlen(s);
	h=root;
	For(i,0,n-1){
		k=s[i]-97;
		while (h!=NULL && h->next[k]==NULL) h=h->fail;
		h=h->next[k];
		tmp=h;
		while (tmp!=NULL){
			if (tmp->count && !tmp->flag){
				tmp->flag=1;
				printf("%d %s\n",i-strlen(tmp->s1)+1,tmp->s1);
			}
			tmp=tmp->fail;
		}
	}
}

int main(){
	int i,j,k,m,n=0;
	root=new node;
	root->fail=NULL;
	while (1){
		gets(p[++n]);
		if (p[n][0]=='\0'){
			n--;
			break;
		}
		insert(p[n]);
	}
	gets(s);
	create_fail();
	auto_search(s);
	return 0;
}

你可能感兴趣的:(AC自动机 (Trie图优化))