Advertisement
LinKin

Aho-Corasick

Feb 7th, 2012
900
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. /*
  2.  * Algorithm: Algorithm of Aho-Corasick
  3.  * Order : O( n )
  4.  * Note: Root is in 0th node
  5.  */
  6. #include<stdio.h>
  7. #include<string.h>
  8. #include<vector>
  9. #include<algorithm>
  10. using namespace std;
  11. #define MAX_ALPH 26
  12. struct NODE{
  13.     char Ch;                // char with which this node reaches
  14.     long Par;               // Parent node
  15.     long Child[MAX_ALPH];   // Child node for coreesponding char
  16.     long State[MAX_ALPH];   // state for coreesponding char
  17.     long Prefix;            // node which is also the longest suffix of Node
  18.     NODE( char Ch = 0,long Par = 0 )
  19.     {
  20.         this->Ch = Ch;
  21.         this->Par = Par;
  22.         memset( Child,-1,sizeof(Child));
  23.         memset( State,-1,sizeof(State));
  24.         Prefix = -1;
  25.     }
  26. };
  27. vector<NODE> Node;
  28.  
  29. void AddString( long I,char *s )
  30. {
  31.     long i,n = 0;
  32.     for( i=0;s[i];i++){
  33.         char Ch = s[i]-'A';
  34.         if( Node[n].Child[Ch]==-1 ){
  35.             Node.push_back( NODE( Ch,n ) );
  36.             Node[n].Child[Ch] = Node.size()-1;
  37.         }
  38.         n = Node[n].Child[Ch];
  39.     }
  40. }
  41. long GoState( long I,char Ch );
  42. /* find the node having path of longest prefix which is also suffiz of I*/
  43. long FindPrefix( long I )
  44. {
  45.     if( Node[I].Prefix==-1 ){
  46.         if( I==0 || Node[I].Par==0 ) Node[I].Prefix = 0;
  47.         else{
  48.             Node[I].Prefix = GoState( FindPrefix( Node[I].Par ) , Node[I].Ch );
  49.         }
  50.     }
  51.     return Node[I].Prefix;
  52. }
  53. /* will return state from I using char CH */
  54. long GoState( long I,char Ch )
  55. {
  56.     if( Node[I].State[Ch]==-1){
  57.         if( Node[I].Child[Ch]!=-1 ) Node[I].State[Ch] = Node[I].Child[Ch];
  58.         else{
  59.             Node[I].State[Ch] = I==0 ? 0:GoState( FindPrefix( I ) , Ch );
  60.         }
  61.     }
  62.     return Node[I].State[Ch];
  63. }
  64.  
  65. int main( void )
  66. {
  67.     Node.resize( 1 );
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement