hdu 4552

ac自动机模版题


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

#define LETTER 26
#define MAXNODE 500005

char key[51],s[100001];

int n,cnt = 0,root;

struct node{
    int count;
    int fail;
    int next[LETTER];
    void init(){memset(next,-1,sizeof(next));count = -1;}
} nd[MAXNODE];

int newnode(){
    nd[cnt].init();
    return cnt++;
}

void insert(const char *str){
    int temp = root;
    for(int i = 0;str[i];i++){
        int c = str[i]-'a';
        if(nd[temp].next[c]==-1) nd[temp].next[c] = newnode();
        temp = nd[temp].next[c];
    }
}


class ACauto{
public:
    ACauto(){cnt = 0;root = newnode();nd[root].fail = root;}
    void getFail(){
        queue<int> q;
        for(int i = 0;i<LETTER;i++){
            int node = nd[root].next[i];
            if(~node){
                nd[node].fail = root;
                q.push(node);
            }
        }
        while(!q.empty()){
            int node = q.front();q.pop();
            for(int i = 0;i<LETTER;i++){
                int nx = nd[node].next[i];
                if(~nx){
                    int nt = nd[node].fail;
                    while(nt!=root&&nd[nt].next[i]==-1) nt = nd[nt].fail;
                    nd[nx].fail = nd[nt].next[i]==-1?root:nd[nt].next[i];
                    q.push(nx);
                }
            }
        }
    }

    int dfs(int cur){
	if(cur==root) return 0;
	if(~nd[cur].count) return nd[cur].count;
	else return 1+dfs(nd[cur].fail);
    }

    int find(){
        int ans = 0;
        int cur = root;
        for(int i = 0;s[i];i++){
            int c = s[i]-'a';
            while(cur!=root&&nd[cur].next[c]==-1) cur = nd[cur].fail;
            cur = nd[cur].next[c]==-1?root:nd[cur].next[c];
	    ans+=dfs(cur);
        }
        return ans;
    }
};

int main(void)
{
    //freopen("2222.in","r",stdin);
    int t;
    scanf("%d",&t);
    while(gets(s)){
        ACauto ac;
    insert(s);
        ac.getFail();
        printf("%d\n",ac.find()%256);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值