bzoj4327

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;
struct triee
{
	int son[4];
	char value;
	char step;
	int  fail,fa;
	bool isright;
};
triee trie[10000020];
char s[10000020];
char temp[1000];
int n, m,root=1;
int diantot = 2;
int num[100020];
int cc(char a)
{
	if (a == 'N')return 0;
	if (a == 'E')return 1;
	if (a == 'S')return 2;
	if (a == 'W')return 3;
}
void insert(char *s, int tot,int kind)
{
	int temp = root;
	for (int i = 0; i < tot; i++)
	{
		int k = cc(s[i]);
		if (trie[temp].son[k] == 0)trie[diantot].step = trie[temp].step+1,trie[diantot].fa=temp,trie[temp].son[k] = diantot++;
		temp = trie[temp].son[k]; trie[temp].value = s[i];
	}
	num[kind] = temp;
}
void getfail()
{
	queue<int>que;
	que.push(1);
	while (!que.empty())
	{
		int now = que.front();
		que.pop();
		for (int i = 0; i < 4; i++)
		{
			int temp = trie[now].son[i];
			int fa = trie[now].fail;
			while (fa&&trie[fa].son[i] == 0)fa = trie[fa].fail;
			if (!temp)
			{
				trie[now].son[i] = trie[fa].son[i];
			}
			else
			{
				trie[temp].fail = trie[fa].son[i];
				que.push(temp);
			}
		}
	}
}
void up(int num)
{
	trie[num].isright = 1;
	num = trie[num].fail;
	while (num&&trie[num].isright == 0)trie[num].isright = 1, num = trie[num].fail;
}
void insertt(char *s, int tot)
{
	int temp = root;
	for (int i = 0; i < tot; i++)
	{
		int k = cc(s[i]);
		int nextt = trie[temp].son[k];
		up(nextt); temp = nextt;
	}
}
int main()
{
	scanf("%d%d", &n, &m);
	int l = 0;
	scanf("%s", s);
	l = strlen(s);
	for (int i = 0; i < m; i++)
	{
	    int tot = 0;
		scanf("%s", temp);
		tot = strlen(temp);
		insert(temp, tot,i);
	}
	for (int i = 0; i < 4; i++)trie[0].son[i] = 1;
	getfail();
	insertt(s, l);
	for (int i = 0; i < m; i++)
	{
		int fa = num[i];
		while (fa&&trie[fa].isright == 0)fa = trie[fa].fa;
		printf("%d\n", trie[fa].step);
	}
	return 0;
}

//改进后的ac自动机

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值