[JSOI2012]玄武密码

传送


这道题就是一个SAM的水题(所以这也是一篇很水的博客)。
我们建完SAM后,把每一个串放上去跑就行了。因为题目要求前缀匹配,所以一旦失配,就直接返回了。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e7 + 5;
const int maxs = 4;
In ll read()
{
	ll ans = 0;
	char ch = getchar(), las = ' ';
	while(!isdigit(ch)) las = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(las == '-') ans = -ans;
	return ans;
}
In void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
	freopen(".in", "r", stdin);
	freopen(".out", "w", stdout);
#endif
}

int n, m, H[105];
char s[maxn];
struct Sam
{
	int tra[maxn << 1][maxs], len[maxn << 1], link[maxn << 1], cnt, las;
	In void init() {link[cnt = las = 0] = -1;}
	In void insert(int c)
	{
		int now = ++cnt, p = las; Mem(tra[now], 0);
		len[now] = len[las] + 1;
		while(~p && !tra[p][c]) tra[p][c] = now, p = link[p];
		if(p == -1) link[now] = 0;
		else
		{
			int q = tra[p][c];
			if(len[q] == len[p] + 1) link[now] = q;
			else
			{
				int clo = ++cnt; 
				len[clo] = len[p] + 1;
				memcpy(tra[clo], tra[q], sizeof(tra[q]));
				link[clo] = link[q], link[q] = link[now] = clo;
				while(~p && tra[p][c] == q) tra[p][c] = clo, p = link[p];
			}
		}
		las = now;
	}
	In int solve(char* s)
	{
		int ret = 0, n = strlen(s);
		for(int i = 0, p = 0, l = 0; i < n && tra[p][H[s[i]]]; ++i) ++ret, p = tra[p][H[s[i]]];
		return ret;
	}
}S;

int main()
{
//	MYFILE();
	n = read(), m = read();
	scanf("%s", s);
	H['E'] = 0, H['W'] = 1, H['S'] = 2, H['N'] = 3;
	S.init();
	for(int i = 0; i < n; ++i) S.insert(H[s[i]]); 
	for(int i = 1; i <= m; ++i)
	{
		scanf("%s", s);
		write(S.solve(s)), enter;
	}
	return 0;	
}
posted @ 2020-10-08 14:57  mrclr  阅读(151)  评论(0编辑  收藏  举报