SP8093 JZPGYZ

/*
打模板题啊
每个串影响到的集合直接枚举跳parent处理即可 

*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#define ll long long 
#define M 400010
#define mmp make_pair
using namespace std;
int read()
{
	int x;
	cin >> x;
	return x;
}
int ch[M][26], fa[M], len[M], cnt = 1, lst, n, m;
string a[M], b; 

void insert(int c)
{
	int p = ++cnt, f = lst;
	lst = p;
	len[p] = len[f] + 1;
	while(f && !ch[f][c]) ch[f][c] = p, f = fa[f];
	if(!f)
	{
		fa[p] = 1;
	}
	else
	{
		int q = ch[f][c];
		if(len[q] == len[f] + 1)
		{
			fa[p] = q;
		}
		else
		{
			int nq = ++cnt;
			fa[nq] = fa[q];
			memcpy(ch[nq], ch[q], sizeof(ch[q]));
			len[nq] = len[f] + 1;
			fa[q] = fa[p] = nq;
			while(f && ch[f][c] == q) ch[f][c] = nq, f = fa[f];
		}
	}
}
int cor[M], ans[M];
int main()
{
	ios::sync_with_stdio(false);	
	n = read(), m = read();
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
		lst = 1;
		for(int j = 0; j < a[i].size(); j++) insert(a[i][j] - 'a');
	}
	for(int i = 1; i <= n; i++)
	{
		int now = 1;
		for(int j = 0; j < a[i].size(); j++)
		{
			now = ch[now][a[i][j] - 'a'];
			int tmp = now;
			while(tmp && cor[tmp] != i) cor[tmp] = i, ans[tmp]++, tmp = fa[tmp]; 
		}
	}
	while(m--)
	{
		cin >> b;
		int now = 1, as = 0;
		for(int i = 0; i < b.size(); i++)
		{
			now = ch[now][b[i] - 'a'];
			if(!now) break;
		}
		as = ans[now];
		cout << as << "
";
	}
	return 0;
}

原文地址:https://www.cnblogs.com/luoyibujue/p/10668838.html