Cod sursa(job #3308075)

Utilizator robert.barbu27robert barbu robert.barbu27 Data 23 august 2025 12:56:16
Problema Aho-Corasick Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.64 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ahocorasick.in");
ofstream fout("ahocorasick.out");
// Pasul 1 e sa construiem trie-ul
char sir[10005];
struct Trie
{
    Trie *fiu[26];
    Trie *backedge;
    int cnt = 0;
    Trie()
    {
        cnt = 0;
        for (int i = 0; i < 26; i++)
        {
            fiu[i] = nullptr;
        }
        backedge = nullptr;
    }
};
Trie *cuvinte[105];
Trie *root = new Trie();
vector<Trie *> nodes;
Trie *insert(Trie *nod, char *s)
{
    if (*s == '\0')
    {
        return nod;
    }
    if (nod->fiu[*s - 'a'] == nullptr)
    {
        nod->fiu[*s - 'a'] = new Trie();
    }
    return insert(nod->fiu[*s - 'a'], s + 1);
}
void BackEdgeBfs()
{
    queue<Trie *> Q;
    Q.push(root);
    while (!Q.empty())
    {
        Trie *nod = Q.front();
       // cout<<1<<'\n';
        nodes.push_back(nod);
        Q.pop();
        for (int i = 0; i < 26; i++)
        {
            if (nod->fiu[i] != nullptr)
            {
                Trie *backedge = nod->backedge;
                while (backedge != nullptr && backedge->fiu[i] == nullptr)
                {
                    backedge = backedge->backedge;
                    //cout<<1<<'\n';
                }
                if (backedge == nullptr)
                {
                    backedge = root;
                }
                else
                {
                    backedge = backedge->fiu[i];
                }
                nod->fiu[i]->backedge = backedge;
                Q.push(nod->fiu[i]);
            }
        }
    }
}
void matchword(string s)
{
    Trie *nod = root;
    for (char c : s)
    {
        // if(nod->fiu[c-'a'] != nullptr){
        //     nod = nod->fiu[c-'a'];
        //     nod->cnt++;
        // }
        while (nod != nullptr && nod->fiu[c - 'a'] == nullptr)
        {
            nod = nod->backedge;
        }
        if (nod == nullptr)
        {
            nod = root;
        }
        else
        {
            nod = nod->fiu[c - 'a'];
        }
        nod->cnt++;
    }
}
void actualizeaza()
{
    while (nodes.size() > 0)
    {
        Trie *nod = nodes.back();
        nodes.pop_back();
        if (nod->backedge != nullptr)
        {
            nod->backedge->cnt += nod->cnt;
        }
    }
}
int main()
{
    string s;
    fin >> s;
    int N;
    fin >> N;
    for (int i = 1; i <= N; i++)
    {
        fin >> sir;
        cuvinte[i] = insert(root, sir);
    }
    BackEdgeBfs();
    matchword(s);
    actualizeaza();
    for(int i=1;i<=N;i++){
        fout<<cuvinte[i]->cnt<<'\n';
    }
}