Bzoj3172: [Tjoi2013]单词

Sol

AC自动机模板题

# 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;
const int _(1e6 + 10);

int n, fail[_], val[_], ch[26][_], tot, ans[210], len, fa[210], Q[_], head = 1, tail;
char s[_];

IL void Insert(RG int id){
	RG int x = 0;
	for(RG int i = 0; i < len; ++i){
		RG int c = s[i] - 'a';
		if(!ch[c][x]) ch[c][x] = ++tot;
		++val[x = ch[c][x]];
	}
	fa[id] = x;
}

IL void Getfail(){
	for(RG int i = 0; i < 26; ++i) if(ch[i][0]) Q[++tail] = ch[i][0];
	while(head <= tail){
		RG int u = Q[head++];
		for(RG int i = 0; i < 26; ++i)
			if(ch[i][u]) fail[ch[i][u]] = ch[i][fail[u]], Q[++tail] = ch[i][u];
			else ch[i][u] = ch[i][fail[u]];
	}
}


int main(RG int argc, RG char *argv[]){
	scanf("%d", &n);
	for(RG int i = 1; i <= n; ++i) scanf(" %s", s), len = strlen(s), Insert(i);
	Getfail();
	for(RG int i = tail; i; --i) val[fail[Q[i]]] += val[Q[i]];
	for(RG int i = 1; i <= n; ++i) printf("%d\n", val[fa[i]]);
	return 0;
}

posted @ 2018-01-09 15:49  Cyhlnj  阅读(73)  评论(0编辑  收藏  举报