Cod sursa(job #2985768)

Utilizator pifaDumitru Andrei Denis pifa Data 27 februarie 2023 01:13:05
Problema Aho-Corasick Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
#define int long long
using namespace std;

ifstream in("ahocorasick.in");
ofstream out("ahocorasick.out");

string b;

int n;

const int N = 1e6 + 5;

int pi[N];

void prefix_function()
{
    int n = b.size();
    pi[0] = 0;
    for(int i = 1; i < n; i++)
    {
        int j = pi[i - 1];
        while(j != 0 && b[j] != b[i])
            j = pi[j - 1];
        if(b[j] == b[i])
            j++;
        pi[i] = j;
    }
}

signed main()
{
    in >> b;
    in >> n;
    string cb = b;
    for(int i = 1; i <= n; i++)
    {
        string a;
        in >> a;
        b = a + "#" + b;
        prefix_function();
        int cnt = 0;
        for(int i = a.size(); i < b.size(); i++)
        {
            if(pi[i] == a.size())
                cnt++;
        }
        out << cnt << '\n';
        memset(pi, 0, sizeof(pi));
        b = cb;
    }
    return 0;
}