AC 自动机

AC自动机

基于字典树Trie,用于多单词匹配问题

struct Trie{
	int to[30];//edge
	int fail,end;//end-cnt(same word with dif id)
}AC[N];
#define root 0
int cnt=0;//point cnt 
inline void build(string s){
	int sz=s.size();
	int pos=root;
	rep0(i,sz){
		if(AC[pos].to[s[i]-'a'])//has edge,move
			pos=AC[pos].to[s[i]-'a'];
		else{//no edge,build new
			AC[pos].to[s[i]-'a']=++cnt;
			pos=cnt;
		}
	}
	AC[pos].end+=1;
}

queue<int> q;

inline void get_fail(){
	rep0(i,26){
		if(AC[root].to[i]){
			AC[AC[root].to[i]].fail=root;
			q.push(AC[root].to[i]);
		}
	}
	while(!q.empty()){//bfs
		int u=q.front();q.pop();
		rep0(i,26){
			if(AC[u].to[i]){
				AC[AC[u].to[i]].fail=AC[AC[u].fail].to[i];//u-->v
				q.push(AC[u].to[i]);
			}
			else AC[u].to[i]=AC[AC[u].fail].to[i];//use for dp
		}
	}
}

inline int match(string s){
	int sz=s.size();
	int pos=root,ans=0;
	rep0(i,sz){
		pos=AC[pos].to[s[i]-'a'];
		for(int j=pos;j&&(AC[j].end!=-1);j=AC[j].fail){//find suf
			ans+=AC[j].end;
			AC[j].end=-1;
		}
	}
	return ans;
}
posted @ 2024-03-01 22:30  Cindy_Li  阅读(20)  评论(0)    收藏  举报