[AC自动机基础题]HDU2222 Keywords Search

AC自动机在trie树上加了fail pointer使得文本串可以不回溯的计算匹配的模板串的个数,每访问一个节点,就将其潜在的与其后缀相等的模板串结果加起来。构建则不赘述。

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int char_num = 26;
int Trie[N][char_num];
int cntword[N];
int fail[N];
int index = 0;

void insert(string s){
    
    
    int p = 0,len = s.size();
    for(int i = 0;i < len;i++){
    
    
        int x = s[i] - 'a';
        if(!Trie[p][x]){
    
    
            Trie[p][x] = ++index;
        }
        p = Trie[p][x];
    }
    cntword[p]++;
}
void construct_fail(){
    
    
    queue<int> q; 
    for(int i = 0;i < 26;i++){
    
    
        if(Trie[0][i]){
    
    
            int node = Trie[0][i];
            fail[node] = 0;
            q.push(node);
        }
    }
    while(!q.empty()){
    
    
        int p_node = q.front();
        q.pop();
        for(int i = 0;i < 26;i++){
    
    
            int now_node = Trie[p_node][i];
            if(now_node){
    
    
                fail[now_node] = Trie[fail[p_node]][i];//important
                q.push(now_node);
            }else
                Trie[p_node][i] = Trie[fail[p_node]][i];//important
        }
    }
}
int quest(string s){
    
    
    int now_node = 0,ans = 0,len = s.size();
    for(int i = 0;i < len;i++){
    
    
        int c = s[i] - 'a';
        now_node = Trie[now_node][c];
        for(int j = now_node;j&&cntword[j] != -1;j = fail[j]){
    
    
            ans += cntword[j];
            cntword[j] = -1;
        }
    }
    return ans;
}
int main(){
    
    
	//freopen("input.txt","r",stdin);
    int t;
    ios::sync_with_stdio(false);
	cin.tie(0);

   	cin>>t;
    while(t--){
    
    
    	int n;
    	cin>>n;
    	index = 0;
    	for(int i = 0;i < n * 50 + 5;i++){
    
    
    		for(int j = 0;j < 26;j++)
    			Trie[i][j] = 0;
    		cntword[i] = fail[i] = 0;
		}
		
    	for(int i = 1;i <= n;i++){
    
    
        	string s;
        	cin>>s;
        	insert(s);
    	}
   	 	construct_fail();
   	 	string text;
    	cin>>text;
    	cout<<quest(text)<<endl;
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_20252251/article/details/108298805