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;
}
标签:AC,end,int,pos,fail,自动机,root
From: https://www.cnblogs.com/Cindy-Li/p/18048105