BotByte

Aho-Corasick

May 3rd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. int n;  // n is the number of dictionary word
  2. string s,p;  // dictionary words are inputted in p, s is the traversed text
  3.  
  4.  
  5. #define MAX_NODE 250004
  6.  
  7. map<char,int> node[MAX_NODE];
  8. int root,nnode,link[MAX_NODE],endof[504],travis[MAX_NODE];
  9. PII level[MAX_NODE];
  10.  
  11. void init()
  12. {
  13.     root=0;
  14.     nnode=0;
  15.     travis[root]=0;  // number of time a node is traversed by s
  16.     level[root]=MP(0,root);  // level, node
  17.     node[root].clear();
  18. }
  19.  
  20. void insertword(int ind)
  21. {
  22.     int len=p.size();
  23.     int now=root;
  24.     REP(i,0,len-1)
  25.     {
  26.         if(!node[now][p[i]])
  27.         {
  28.             node[now][p[i]]=++nnode;
  29.             node[nnode].clear();
  30.             travis[nnode]=0;
  31.             level[nnode]=MP(level[now].first+1,nnode);
  32.         }
  33.         now=node[now][p[i]];
  34.     }
  35.     endof[ind]=now;  // end of dictionary word ind
  36. }
  37.  
  38. void push_links()
  39. {
  40.     queue<int>q;
  41.     link[0]=-1;
  42.     q.push(0);
  43.     while(!q.empty())
  44.     {
  45.         int u=q.front();
  46.         q.pop();
  47.         itrALL(node[u],it)
  48.         {
  49.             char ch=it->first;
  50.             int v=it->second;
  51.             int j=link[u];
  52.             while(j!=-1 && !node[j][ch])j=link[j];
  53.             if(j!=-1)link[v]=node[j][ch];
  54.             else link[v]=0;
  55.             q.push(v);
  56.         }
  57.     }
  58. }
  59.  
  60. void traverse()
  61. {
  62.     int len=s.size();
  63.     int now=root;
  64.     travis[root]++;
  65.     REP(i,0,len-1)
  66.     {
  67.         while(now!=-1 && !node[now][s[i]])now=link[now];
  68.         if(now!=-1)now=node[now][s[i]];
  69.         else now=0;
  70.         travis[now]++;
  71.     }
  72.     sort(level,level+nnode+1,greater<PII>());
  73.     REP(i,0,nnode)
  74.     {
  75.         now=level[i].second;
  76.         travis[link[now]]+=travis[now];
  77.     }
  78. }
  79.  
  80.  
  81. void driver()
  82. {
  83.     init;
  84.     REP(i,1,n)
  85.     {
  86.         // input p
  87.         insertword(i);
  88.     }
  89.     // input s
  90.     push_links();
  91.     traverse();
  92.     // number of occurence of word i in s is travis[endof[i]]
  93. }
Add Comment
Please, Sign In to add comment