AC自动机 模板

测试题目:HDU 2222,

const int maxn = 10000 * 50 + 50,sigma_size = 26;

/** AC_AUTOMATION */
int ch[maxn][sigma_size],fail[maxn],tot;
int value[maxn];

/** 初始化 */
void Init(){
    memset(ch[0],0,sizeof ch[0]);
    tot = 1;
    fail[0] = -1;value[0] = 0;
}

/** 插入字符串 s */
void Insert(char* s){
    int idx,cur = 0;
    while( *s ){
        idx = *s - 'a';
        if(ch[cur][idx] == 0){
            memset(ch[tot],0,sizeof ch[tot]);
            fail[tot] = 0;
            value[tot] = 0;
            ch[cur][idx] = tot++;
        }
        cur = ch[cur][idx];
        s++;
    }
    value[cur]++;
}

/** GetFail */
void GetFail(){
    queue<int> Q;
    Q.push(0);
    fail[0] = -1;
    int cur,idx,f;
    while(!Q.empty()){
        cur = Q.front();Q.pop();
        for(int i = 0;i < sigma_size;++i){
            if(ch[cur][i]){
                f = fail[cur];
                while(f != -1 && ch[f][i] == 0) f = fail[f];
                fail[ch[cur][i]] = (f == -1) ? 0 : ch[f][i];
                Q.push(ch[cur][i]);
            }
            else{
                f = fail[cur];
                ch[cur][i] = (f == -1) ? 0 : ch[f][i];
            }
        }
    }
}
/**  以上具有通用性 */
/** 匹配 */
int Search(char *s){
    int cur = 0,idx,ret = 0,tmp;
    while(*s){
        idx = *s - 'a';
        tmp = cur = ch[cur][idx];
        if(value[tmp]) while(tmp){
            ret += value[tmp];value[tmp] = 0;
            tmp = fail[tmp];
        }
        s++;
    }
    return ret;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值