HDU2222(AC自动机模板题)

Aho-Corasick automaton,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法。
AC自动机是字典树和KMP的结合。
可以解决的问题:给定多个单词,再给一个字符串,问有多少个单词在这个字符串中出现过。
这个问题可以用KMP挨个串匹配,但是如果单词数目多的话肯定会超时。
数中节点:
struct node{
	node *next[26];
	node *fail;
	int sum;
};
sum统计以该字母结尾的单词数目。fail指针相当于KMP中的next数组。
具体可以看这篇文章,讲的不错: http://blog.csdn.net/creatorx/article/details/71100840

题目: HDU2222
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
using namespace std;
const int N = 10005;
const int L1 = 52;
const int L2 = 1000005;

struct node{
	node *next[26];
	node *fail;
	int sum;
};
node *root;
queue<node*> Q;
void init(){
	root = (node*)malloc(sizeof(node));
	for(int i = 0; i < 26; i++)
		root->next[i] = NULL;
	root->fail = NULL;
	root->sum = 0;
	while(!Q.empty())Q.pop();
}
void insert(char *str){
	node *tmp = root, *p;
	int len = strlen(str);
	for(int i = 0; i < len; i++){
		int x = str[i] - 'a';
		if(tmp->next[x] == NULL){
			p = (node*)malloc(sizeof(node));
			for(int j = 0; j < 26; j++)
				p->next[j] = NULL;
			p->fail = NULL;
			p->sum = 0;
			tmp->next[x] = p;
		}
		tmp = tmp->next[x];
	}
	tmp->sum++;
}
void build(){
	node *p, *tmp;
	Q.push(root);
	while(!Q.empty()){
		tmp = Q.front();
		Q.pop();
		for(int i = 0; i < 26; i++){
			if(tmp->next[i] == NULL) continue;
			if(tmp == root){
				tmp->next[i]->fail = root;
			}
			else{
				p = tmp->fail;
				while(p){
					if(p->next[i]){
						tmp->next[i]->fail = p->next[i];
						break;
					}
					p = p->fail;
				}
				if(!p) tmp->next[i]->fail = root;
			}
			Q.push(tmp->next[i]);
		}
	}
}
int ac_automation(char *str){
	int cnt = 0;
	node *tmp, *p = root;
	int len = strlen(str);
	for(int i = 0; i < len; i++){
		int x = str[i] - 'a';
		while(p != root && p->next[x] == NULL)
			p = p->fail;
		p = p->next[x];
		if(!p) p = root;
		tmp = p;
		while(tmp != root){
			if(tmp->sum >= 0){
				cnt += tmp->sum;
				tmp->sum = -1;
			}
			else
				break;
			tmp = tmp->fail;
		}
	}
	return cnt;
}
int main(){
	int t, n;
	char str1[L1];
	char str2[L2];
	scanf("%d", &t);
	while(t--){
		init();
		scanf("%d", &n);
		for(int i = 0; i < n; i++){
			scanf("%s", str1);
			insert(str1);
		}
		build();
		scanf("%s", str2);
		int cnt = ac_automation(str2);
		printf("%d\n", cnt);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值