AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 校园
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

AcWing 1282. 搜索关键词

作者: 作者的头像   imnoob ,  2022-01-15 15:16:45 ,  所有人可见 ,  阅读 8


0


#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 10010, S = 55, M = 1e6 + 10;
int tr[N * S][26], cnt[N * S];
char str[M];
int q[N * S], ne[N * S];
int idx;

void insert()  // 将str插入tr中
{
    int p = 0;
    for(int i = 0;str[i];++i){
        int u = str[i] - 'a';
        if(!tr[p][u]) tr[p][u] = ++idx;
        p = tr[p][u];
    }
    cnt[p]++;
}

void build()  // 创建AC自动机
{
    int hh = 0, tt = -1;
    for(int i = 0;i < 26;i ++){
        if(tr[0][i]) q[++ tt] = tr[0][i];
    }

    while(hh <= tt){
        int t = q[hh ++];
        for(int i = 0;i < 26;i ++){
            if(!tr[t][i]){
                tr[t][i] = tr[ne[t]][i];
            }else{
                 ne[tr[t][i]] = tr[ne[t]][i];
                q[++tt] = tr[t][i];
            }
        }
    }
}

void sol(){
    memset(tr, 0, sizeof tr);
    memset(cnt, 0, sizeof cnt);
    memset(ne, 0, sizeof ne);
    idx = 0;
    int n;cin >> n;

    for(int i = 0;i < n;i ++){
        cin >> str;
        insert();
    }
    build();

    cin >> str;
    int res = 0;

    for(int i = 0,j = 0;str[i];i ++){
        int t = str[i] - 'a';
        j = tr[j][t];
        int p = j;
        while(p){
            res += cnt[p];
            cnt[p] = 0;
            p = ne[p];
        }
    }
    cout << res << '\n';
}

int main(){
    int t;
    cin >> t;
    while(t --)
        sol();
}

0 评论

你确定删除吗?
1024
x

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息