【TJOI2013】 单词

4 篇文章 0 订阅
2 篇文章 0 订阅

【题目链接】

         点击打开链接

【算法】

         AC自动机+递推

【代码】

       

#include<bits/stdc++.h>
using namespace std;
#define MAXN 200
const int MAXL = 1e6+5;

int i,N;
int pos[MAXN+10];
char s[MAXN+1][MAXL];

template <typename T> inline void read(T &x) {
	int f = 1; x = 0;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}

template <typename T> inline void write(T x) {
	if (x < 0) { putchar('-'); x = -x; }
	if (x > 9) write(x/10);
	putchar(x%10+'0');
}

template <typename T> inline void writeln(T x) {
	write(x);
	puts("");
}

struct AC_Automation {
	int tot;
	struct Trie {
		int sum,fail;
		int next[26];
	} trie[MAXL];
	inline void Insert(int id,char *s) {
		int i,len,x,root=0;
		len = strlen(s);
		for (i = 0; i < len; i++) {
			x = s[i] - 'a';
			if (!trie[root].next[x]) trie[root].next[x] = ++tot;
			root = trie[root].next[x];
			++trie[root].sum;
		}
		pos[id] = root;
	}
	inline void rebuild() {
		int i,root,tmp,l=1,r=1;
		static int q[MAXL];
		q[1] = 0;
		trie[0].fail = -1;
		while (l <= r) {
			root = q[l]; l++;
			for (i = 0; i < 26; i++) {
				if (trie[root].next[i]) {
					if (!root)
						trie[trie[root].next[i]].fail = 0;
					else {
						tmp = trie[root].fail;
						while (tmp != -1) {
							if (trie[tmp].next[i]) {
								trie[trie[root].next[i]].fail = trie[tmp].next[i];
								break;
							} 
							tmp = trie[tmp].fail;
						}
						if (tmp == -1) trie[trie[root].next[i]].fail = 0;
					}
					q[++r] = trie[root].next[i];
				}
			}
		}
		for (i = r; i >= 1; i--) trie[trie[q[i]].fail].sum += trie[q[i]].sum;
	}	
	inline void output() {
		int i;
		for (i = 1; i <= N; i++) writeln(trie[pos[i]].sum);
	}
} ACAM;

int main() {
	
	read(N);
	for (i = 1; i <= N; i++) {
		gets(s[i]);
		ACAM.Insert(i,s[i]);	
	}
	ACAM.rebuild();
	ACAM.output();
	
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值