bzoj3172 单词 AC自动机

来源:互联网 发布:淘宝联盟使用红包 编辑:程序博客网 时间:2024/06/08 06:54

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

AC代码如下:

#include<iostream>#include<cstdio>#include<cstring>#define N 1100005using 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

0 0
原创粉丝点击