您的位置:首页 > 其它

AC自动机模板

2015-09-03 18:36 337 查看
struct ACauto{
int ch[maxn][26];
int sz;
int f[maxn],last[maxn],val[maxn],cnt[maxn];
void init(){
sz=1;
memset(ch[0],0,sizeof ch[0]);
memset(cnt,0,sizeof cnt);
}
int idx(char c){
return c-'A';
}
void add(char *s,int v){
int u=0,len=strlen(s);
for(int i=0;i<len;i++){
int c=idx(s[i]);
if(!ch[u][c]){
memset(ch[sz],0,sizeof ch[sz]);
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=v;
}
void getfail(){
queue<int>q;
f[0]=0;
for(int c=0;c<26;c++){
int u=ch[0][c];
if(u){
f[u]=0;
q.push(u);
last[u]=0;
}
}
while(!q.empty()){
int r=q.front();q.pop();
for(int c=0;c<26;c++){
int u=ch[r][c];
if(!u){
ch[r][c]=ch[f[r]][c];
continue;
}
q.push(u);
f[u]=ch[f[r]][c];
last[u]=val[f[u]]?f[u]:last[f[u]];
}
}
}
void print(int j){
if(j){
cnt[val[j]]++;
print(last[j]);
}
}
void Find(char *T){
int n=strlen(T);
int j=0;
for(int i=0;i<n;i++){
int c=idx(T[i]);
while(j&&!ch[j][c])j=f[j];
j=ch[j][c];
if(val[j])print(j);
else if(last[j])print(last[j]);
}
}
}ac;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: