题目链接: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;
}