[TJOI2013]单词 AC自动机

本文介绍了一种使用AC自动机解决单词计数问题的方法。通过构建AC自动机并进行匹配,可以高效统计一篇论文中各单词出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
一篇论文是由许多单词组成但小张发现一个单词会在论文中出现很多次,他想知道每个单词分别在论文中出现了多少次。


Sample Input
3
a
aa
aaa


Sample Output
6
3
1


这道题,AC自动机裸题。。。
你建好AC自动机,再把所有s从最底层和上来。


#include <cstdio>
#include <cstring>

using namespace std;
int _max(int x, int y) {return x > y ? x : y;}
const int maxn = 1100000;

struct node {
    int pp, s, fail, v[30];
    node() {memset(v, -1, sizeof(v));}
} t[maxn]; int cnt, list[maxn];
int cc[maxn];
char ss[maxn];

void bt(int now) {
    int x = 0;
    int len = strlen(ss + 1);
    for(int i = 1; i <= len; i++) {
        int y = ss[i] - 'a' + 1;
        if(t[x].v[y] == -1) t[x].v[y] = ++cnt;
        t[x].s++; x = t[x].v[y];
    } t[x].s++;
    cc[now] = x;
}

void get_fail() {
    int head = 1, tail = 2;
    list[1] = 0;
    while(head != tail) {
        int x = list[head];
        for(int i = 1; i <= 26; i++) {
            int y = t[x].v[i];
            if(y == -1) continue;
            if(x == 0) t[y].fail = 0;
            else {
                int j = t[x].fail;
                while(j && t[j].v[i] == -1) j = t[j].fail;
                t[y].fail = _max(0, t[j].v[i]);
            }
            list[tail++] = y;
        }
        head++;
    }
    for(int i = tail; i >= 1; i--) t[t[list[i]].fail].s += t[list[i]].s;
}

int main() {
    int n; scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%s", ss + 1);
        bt(i);
    }
    get_fail();
    for(int i = 1; i <= n; i++) printf("%d\n", t[cc[i]].s);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值