zoukankan      html  css  js  c++  java
  • AC自动机模板

    AC自动机模板

    只有靠打打板子才能维持得了生活

    
    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e6+10;
    char s[N];
    struct AC_{
    	int ch[N][26],size;
    	int end[N],fail[N];
    	void insert(char *s){
    		int len=strlen(s),p=0;
    		for(int i=0;i<len;i++){
    			int c=s[i]-'a';
    			if(!ch[p][c])ch[p][c]=++size;
    			p=ch[p][c];
    		}
    		end[p]++;
    	}
    	void build(){
    		queue<int>q;
    		memset(fail,0,sizeof(fail));
    		for(int i=0;i<26;i++){
    			if(ch[0][i])q.push(ch[0][i]);
    		}
    		while(!q.empty()){
    			int u=q.front();q.pop();
    			for(int c=0;c<26;c++){
    				if(ch[u][c])fail[ch[u][c]]=ch[fail[u]][c],q.push(ch[u][c]);
    				else ch[u][c]=ch[fail[u]][c];
    			}
    		}
    	}
    	int query(char *t){
    		int p=0,res=0;
    		for(int i=0;t[i];i++){
    			p=ch[p][t[i]-'a'];
    			for(int j=p;j&&~end[j];j=fail[j])res+=end[j],end[j]=-1;
    		}
    		return res;
    	}
    }ac;
    int main(){
    	int n;scanf("%d",&n);
    	for(int i=1;i<=n;i++){
    		scanf("%s",s);
    		ac.insert(s);
    	}
    	ac.build();
    	scanf("%s",s);
    	cout<<ac.query(s)<<endl;
    }
    
    
    
    
  • 相关阅读:
    PHP 数据库 ODBC
    PHP MySQL Delete
    PHP MySQL Update
    PHP MySQL Order By 关键词
    PHP MySQL Where 子句
    01_今日介绍
    00_前情回顾
    02_cfork分叉进程
    01_c++下jni开发说明
    17_activity任务栈和启动模式
  • 原文地址:https://www.cnblogs.com/soda-ma/p/13485282.html
Copyright © 2011-2022 走看看