Computer Virus on Planet Pandora (AC自动机模板题)

思路:AC自动机正着扫一遍,反着扫一遍。

WA:合成字符串str2时,未进行末尾赋0,导致上次数据保留了下来。

//936ms
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxs = 5100010,maxp = 1010,maxn = 260010,alpha = 26;

int pc,f[maxn],ch[maxn][alpha],flag[maxn];
char ptr[maxp],str[maxs],str2[maxs];

void ins(char *p)                    //建树
{
	int n = strlen(p),cur = 0;
	for(int i=0;i<n;++i)
	{
		int v = p[i] - 'A';
		if(!ch[cur][v]) ch[cur][v] = ++pc;
		cur = ch[cur][v];
	}
	flag[cur]++;
}
void getfail()                        //bfs找失配函数f
{
	queue<int> q;
	f[0] = 0;
	for(int c=0;c<alpha;++c)
	{
		int u = ch[0][c];
		if(u){
			q.push(u);f[u] = 0;
		}
	}
	while(!q.empty())
	{
		int r = q.front();q.pop();
		for(int c=0;c<alpha;++c)
		{
			int u = ch[r][c];
			if(!u) continue;
			q.push(u);
			int v = f[r];
			while(v && !ch[v][c]) v = f[v];
			f[u] = ch[v][c];
		}
	}
}
int find(char *s)
{
	int n = strlen(s);
	int j = 0,cnt = 0;
	for(int i=0;i<n;++i)
	{
		int c = s[i] - 'A';
		while(j && !ch[j][c]) j = f[j];
		j = ch[j][c];
		int tmp = j;
		while(flag[tmp])
		{
			cnt += flag[tmp];
			flag[tmp] = 0;
			tmp = f[tmp];
		}
	}
	return cnt;
}
int main()
{
	int n,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		while(n--)
		{
			scanf(" %s",ptr);
			ins(ptr);
		}
		getfail();
		scanf(" %s",str);
		int j = 0;
		for(int i=0;str[i];++i){            //不规则字符串转化
			if(str[i] >= 'A' && str[i] <= 'Z') str2[j++] = str[i];
			else
			{
				++i;
				int cnt = 0;
	            while (str[i]<'A'||str[i]>'Z')
	            {
	                cnt = cnt*10 + (str[i]-'0');    //数字部分不止一位
	                ++i;
	            }
				while(cnt--){
					str2[j++] = str[i];
				}
				++i;
			}
		}
		str2[j] = 0;                                 //重要的末尾清0
		int ans = 0;
		ans += find(str2);
		strrev(str2);                                //strrev(),反转串,reverse
		ans += find(str2);
		printf("%d\n",ans);
		pc = 0;
		memset(flag,0,sizeof(flag));
		memset(ch,0,sizeof(ch));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值