bzoj3172 单词 AC自动机

      (感觉以前写过。。bzoj上不去我也不知道) 跑一遍AC自动机,每一个节点保存一下属于多少字符串,为它的权值。然后一个节点表示的字符串在整个字典中出现的次数相当于其在Fail树中的子树的权值的和。AC自动机不要写挂就好了。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#define N 1100005
using namespace std;

char s[N]; int n,a[N],h[N];
struct acam_node{
	int cnt,last,ch[N][26],sz[N],fail[N];
	void add(int x){
		scanf("%s",s+1); int now=0,i,len=strlen(s+1);
		for (i=1; i<=len; i++){
			int c=s[i]-'a'; if (!ch[now][c]) ch[now][c]=++cnt;
			now=ch[now][c]; sz[now]++;
		}
		a[x]=now;
	}
	void build(){
		int i,head=0,tail=0;
		for (i=0; i<26; i++) if (ch[0][i]) h[++tail]=ch[0][i];
		while (head<tail){
			int x=h[++head],y;
            	for (i=0; i<26; i++) if (y=ch[x][i]){
				h[++tail]=y; fail[y]=ch[fail[x]][i];
			} else ch[x][i]=ch[fail[x]][i];
		}
	}
	void solve(){
		int i; for (i=cnt; i>=0; i--) sz[fail[h[i]]]+=sz[h[i]];
		for (i=1; i<=n; i++) printf("%d\n",sz[a[i]]);
	}
}acam;
int main(){
	scanf("%d",&n); int i;
	for (i=1; i<=n; i++) acam.add(i);
	acam.build(); acam.solve();
	return 0;
}

by lych

2016.2.18

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值