hdu 3065 病毒侵袭持续中

继续AC自动机水题。

这个题与上个题区别在于,需要统计出现次数,所以不能统计下就标记然后下次就不统计了,就比如样例AAA,出现AA是两次的。

再者就是,匹配串还有其他字符,需要判断一下,遇到其他字符的时候,直接指针移动到root。刚开始开了130个指针,果断MLE了。。

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define BUG puts("here!!!")
#define STOP system("pause")

using namespace std;

const int MAX_N = 26;

struct NODE{
	int id;
	NODE *next[MAX_N], *fail;
	NODE()
	{
		id = -1;
		fail = NULL;
		memset(next, 0, sizeof(next));
	}
}*head;

void Build_trie(char *s,NODE *head,int id)
{
	int len = strlen(s);
	for(int i=0; i<len; i++)
	{
		int k = s[i] - 'A';
		if( head->next[k] == NULL )
			head->next[k] = new NODE();
		head = head->next[k];
	}
	head->id = id;
}

queue<NODE*> q;
void Build_fail(NODE *head)
{
	head->fail = NULL;
	q.push(head);
	while( !q.empty() )
	{
		NODE *now = q.front(); q.pop();
		for(int i=0; i<MAX_N; i++)
			if( now->next[i] )
			{
				NODE *p = now->fail;
				while( p )
				{
					if( p->next[i] )
					{
						now->next[i]->fail = p->next[i];
						break;
					}
					p = p->fail;
				}
				if( p == NULL )
					now->next[i]->fail = head;
				q.push(now->next[i]);
			}
						
	}
}

int cnt[1010];
void AC_find(NODE *head, char *s)
{
	int len = strlen(s), sum = 0;
	NODE* p = head;
	for(int i=0; i<len; i++)
	{
		if( !isupper(s[i]) )
		{
			p = head;
			continue;
		}
		int k = s[i] - 'A';
		while( p->next[k] == NULL && p != head )
			p = p->fail;
		p = p->next[k] == NULL ? head : p->next[k];
		
		NODE *tmp = p;
		while( tmp != head )
		{
			if( tmp->id != -1 )
				cnt[tmp->id]++;
			tmp = tmp->fail;
		}
	}
}

char s[2000005];
char ss[1010][55];

int main()
{
	int n;
	
	while( ~scanf("%d", &n) )
	{	
		head = new NODE();
		for(int i=0; i<n; i++)
		{
			scanf("%s", ss[i]);
			Build_trie(ss[i], head, i);
		}
		
		Build_fail( head );
		
		scanf("%s", s);
		memset(cnt, 0, sizeof(cnt));
		AC_find( head, s);
		
		for(int i=0; i<n; i++)
			if( cnt[i] )
				printf("%s: %d\n",ss[i], cnt[i]);
	}

return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值