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 }