zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    实战分享 | 你知道这个死锁是怎么产生的吗?
    HDU 3016 线段树区间更新+spfa
    POJ 2828 线段树(想法)
    POJ 2184 01背包+负数处理
    HDU 2955 01背包(思维)
    HDU 1171 背包
    HDU 1561 树形DP入门
    POJ 3694 tarjan 桥+lca
    POJ 2446 最小点覆盖
    POJ 2226 最小点覆盖(经典建图)
  • 原文地址:https://www.cnblogs.com/Empress/p/4632083.html
Copyright © 2011-2022 走看看