java版AC自动机

 1 class Trie
 2 {
 3     int [][]Next=new int[500005][128];
 4     int []fail=new int[500005];
 5     int []end=new int[500005];
 6     int root, L;
 7     int newnode()
 8     {
 9         for(int i=0;i<128;i++)
10             Next[L][i]=-1;
11         end[L++]=0;
12         return L-1;
13     }
14     void init()
15     {
16         L=0;
17         root=newnode();
18     }
19     void insert(byte buf[], int id)
20     {
21         int now=root;
22         for(int i=0; i<buf.length; i++)
23         {
24             if(Next[now][buf[i]]==-1)
25                 Next[now][buf[i]]=newnode();
26             now=Next[now][buf[i]];
27         }
28         end[now]=id;
29     }
30     void build()
31     {
32         Queue<Integer> q=new LinkedList<Integer>();
33         fail[root]=root;
34         for(int i=0; i<128; i++)
35         {
36             if(Next[root][i]==-1)
37                 Next[root][i]=root;
38             else
39             {
40                 fail[Next[root][i]]=root;
41                 q.add(Next[root][i]);
42             }
43         }
44         while(!q.isEmpty())
45         {
46             int now=q.poll();
47             for(int i=0; i<128; i++)
48             {
49                 if(Next[now][i]==-1)
50                     Next[now][i]=Next[fail[now]][i];
51                 else
52                 {
53                     fail[Next[now][i]]=Next[fail[now]][i];
54                     q.add(Next[now][i]);
55                 }
56             }
57         }
58     }
59     int query(byte buf[], int n, String s[])
60     {
61         int now=root;
62         int ans=0;
63         for(int i=0; i<buf.length; i++)
64         {
65             now=Next[now][buf[i]];
66             int temp=now;
67             while(temp!=root)
68             {
69                 ans+=end[temp];
70                 end[temp]=0;    
71                 temp=fail[temp];
72             }
73         }
74         return ans;
75     }
76 }
View Code

 

转载于:https://www.cnblogs.com/Empress/p/4632083.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值