Bzoj2780: [Spoj]8093 Sevenk Love Oimaster

题目

传送门

Sol

就是广义\(sam\)
然后记录下每个状态属于哪些串,开\(set\)维护
\(parent\)树上启发式合并一下就好了

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
 
IL int Input(){
    RG int x = 0, z = 1; RG char c = getchar();
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

const int maxn(2e5 + 5);

int trans[26][maxn], fa[maxn], len[maxn], size[maxn], last, tot = 1;
int l[maxn], r[maxn], n, q, t[maxn], id[maxn];
set <int> :: iterator it;
set <int> ed[maxn];
char s[maxn], qs[maxn << 1];

IL void Extend(RG int c){
	RG int p = last, np = ++tot;
	len[last = np] = len[p] + 1;
	while(p && !trans[c][p]) trans[c][p] = np, p = fa[p];
	if(!p) fa[np] = 1;
	else{
		RG int q = trans[c][p];
		if(len[q] == len[p] + 1) fa[np] = q;
		else{
			RG int nq = ++tot;
			fa[nq] = fa[q], len[nq] = len[p] + 1;
			for(RG int i = 0; i < 26; ++i) trans[i][nq] = trans[i][q];
			fa[q] = fa[np] = nq;
			while(p && trans[c][p] == q) trans[c][p] = nq, p = fa[p];
		}
	}
}

int main(){
	n = Input(), q = Input();
	for(RG int i = 1; i <= n; ++i){
		l[i] = r[i - 1];
		scanf(" %s", s + l[i]);
		r[i] = l[i] + strlen(s + l[i]), last = 1;
		for(RG int j = l[i]; j < r[i]; ++j) Extend(s[j] - 'a');
	}
	for(RG int i = 1; i <= tot; ++i) ++t[len[i]];
	for(RG int i = 1; i <= tot; ++i) t[i] += t[i - 1];
	for(RG int i = 1; i <= tot; ++i) id[t[len[i]]--] = i;
	for(RG int i = 1; i <= n; ++i)
		for(RG int j = l[i], nw = 1; j < r[i]; ++j){
			nw = trans[s[j] - 'a'][nw];
			ed[nw].insert(i);
		}
	for(RG int i = tot; i; --i){
		RG int p = id[i];
		size[p] = ed[p].size();
		if(size[p] > ed[fa[p]].size()) swap(ed[p], ed[fa[p]]);
		for(it = ed[p].begin(); it != ed[p].end(); ++it)
			ed[fa[p]].insert(*it);
	}
	for(RG int i = 1; i <= q; ++i){
		scanf(" %s", qs);
		RG int nw = 1, l = strlen(qs);
		for(RG int j = 0; j < l; ++j) nw = trans[qs[j] - 'a'][nw];
		printf("%d\n", size[nw]);
	}
	return 0;
}
posted @ 2018-04-25 10:52  Cyhlnj  阅读(105)  评论(0编辑  收藏  举报