2015多校第8场 HDU 5384 Danganronpa AC自动机

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5384

题意:

f(A,B)表示:B在A中作为子串出现的次数。
题目给出n个证据,m个子弹
Ai是证据,Bi是子弹,题目问:所有Bi对每个Ai造成的伤害是多少,即每个Bi在Ai中出现的次数总和。

解法:AC自动机裸题


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+10;
const int M = 5e5+10;
const int S = 26;
int n;
char s[N];
string s1[N];
string s2[N];
struct AcAutomata{
    int root,sz;
    int nxt[M][S],fail[M],cnt[M];
    int newnode(){
        cnt[sz] = 0;
        memset(nxt[sz], -1, sizeof(nxt[sz]));
        return sz++;
    }
    void init(){
        sz = 0;
        root = newnode();
    }
    void insert(char *s){
        int u = root;
        int n = strlen(s);
        for(int i=0; i<n; i++){
            int &v = nxt[u][s[i]-'a'];
            if(v==-1) v=newnode();
            u=v;
        }
        ++cnt[u];
    }
    void build(){
        queue <int> q;
        fail[root] = root;
        for(int i=0; i<S; i++){
            int &v = nxt[root][i];
            if(~v){
                fail[v] = root;
                q.push(v);
            }
            else{
                v = root;
            }
        }
        while(q.size()){
            int u = q.front(); q.pop();
            for(int i = 0; i < S; i++){
                int &v = nxt[u][i];
                if(~v){
                    fail[v] = nxt[fail[u]][i];
                    q.push(v);
                    cnt[v] += cnt[fail[v]];
                }
                else{
                    v = nxt[fail[u]][i];
                }
            }
        }
    }
    LL query(string s){
        LL ans = 0;
        int u = root, n = s.size();
        for(int i=0; i<n; i++){
            u = nxt[u][s[i]-'a'];
            ans += cnt[u];
        }
        return ans;
    }
}ZXY;

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int n, m;
        scanf("%d %d", &n,&m);
        for(int i=1; i<=n; i++) cin>>s1[i];
        ZXY.init();
        for(int i=1; i<=m; i++) scanf("%s", s), ZXY.insert(s);
        ZXY.build();
        for(int i=1; i<=n; i++){
            LL ans  = ZXY.query(s1[i]);
            printf("%lld\n", ans);
        }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值