HDU-2222 Keywords Search(AC自动机,不懂strlen放在函数中为什么会超时)

AC自动机模板,不过超时了很多次,参考了别人的代码后,起初把strlen放在insert()和query()中,后面strlen放在参数中就过了。

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int N = 5e5 + 100;
const int M = 1e6 + 5;
int trie[N][26]; //字典树
int cntword[N];  //记录该单词出现次数
int fail[N];     //失败时的回溯指针
int tot = 0;
char s[M];
void insertWords(char *s, int l){
    int root = 0;
    for(int i = 0; i < l; ++i){
        int next = s[i] - 'a';
        if(!trie[root][next])
            trie[root][next] = ++tot;
        root = trie[root][next];
    }
    ++cntword[root];      //当前节点单词数+1
}
void getFail(){
    queue<int> q;
    for(int i = 0; i < 26; ++i){      //将第二层所有出现了的字母扔进队列
        if(trie[0][i]){
            fail[trie[0][i]] = 0;
            q.push(trie[0][i]);
        }
    }

//fail[now]    ->当前节点now的失败指针指向的地方
tire[now][i] -> 下一个字母为i+'a'的节点的下标为tire[now][i]
    while(!q.empty()){
        int now = q.front();
        q.pop();

        for(int i = 0; i < 26; ++i){      //查询26个字母
            if(trie[now][i]){
                //如果有这个子节点为字母i+'a',则
//让这个节点的失败指针指向(((他父亲节点)的失败指针所指向的那个节点)的下一个节点)
                //有点绕,为了方便理解特意加了括号

                fail[trie[now][i]] = trie[fail[now]][i];
                q.push(trie[now][i]);
            }
            else//否则就让当前节点的这个子节点
                //指向当前节点fail指针的这个子节点
                trie[now][i] = trie[fail[now]][i];
        }
    }
}


int query(char *s, int l){
    int now = 0,ans = 0;
    for(int i = 0; i < l; ++i){    //遍历文本串
        now = trie[now][s[i] - 'a'];  //从s[i]点开始寻找
        for(int j = now; j && cntword[j] != -1; j = fail[j]){
            //一直向下寻找,直到匹配失败(失败指针指向根或者当前节点已找过).
            ans += cntword[j];
            cntword[j] = -1;    //将遍历国后的节点标记,防止重复计算
        }
    }
    return ans;
}

void init(){
	memset(cntword, 0, sizeof(cntword));
	memset(trie, 0, sizeof(trie));
	tot = 0;
}
int main() {
	int t;
	scanf("%d", &t);
	while(t--){
	    int n;
	    scanf("%d", &n);
	    for(int i = 0; i < n; ++i){
	        scanf("%s", s);
	        insertWords(s, strlen(s));
	    }
	    fail[0] = 0;
	    getFail();
	    scanf("%s", s);
	    printf("%d\n", query(s, strlen(s)));
	    init();
	}
    return 0;
}

/*
1
5
she
he
say
shr
her
yasherhs

*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值