Cod sursa(job #2523166)

Utilizator radugheoRadu Mihai Gheorghe radugheo Data 13 ianuarie 2020 20:03:18
Problema Aho-Corasick Scor 25
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <bits/stdc++.h>
#define DIM 10005

using namespace std;

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

struct trie {
    int sol;
    trie *f[26];
    trie *last;
    vector <trie *> v;
    trie(){
        sol = 0;
        last = 0;
        v.clear();
        for (int i=0; i<26; i++){
            f[i] = 0;
        }
    }
};

trie *rad = new trie();
trie *w[105], *nod, *aux, *vecin;

char c[DIM*100], s[DIM];

queue <trie *> q;

int n;

trie *adauga (trie *rad, char *s){
    if (*s == 0){
        return rad;
    }
    if (rad->f[*s-'a'] == NULL){
        rad->f[*s-'a'] = new trie();
    }
    return adauga (rad->f[*s-'a'], s+1);
}

void dfs (trie *nod){
    for (int i=0; i<nod->v.size(); i++){
        dfs (nod->v[i]);
        nod->sol += nod->v[i]->sol;
    }
}

int main(){
    fin >> c;
    fin >> n;
    for (int i=1; i<=n; i++){
        fin >> s;
        w[i] = adauga (rad, s);
    }
    q.push(rad);
    while (!q.empty()){
        nod = q.front();
        q.pop();
        for (int i=0; i<26; i++){
            if (nod->f[i]){
                //construiesc last-ul pentru vecinul nodului practic
                aux = nod->last;
                while (aux && aux->f[i] == NULL){
                    aux = aux->last;
                }
                if (aux == 0){
                    nod->f[i]->last = rad;
                }
                else{
                    nod->f[i]->last = aux->f[i];
                }
                nod->f[i]->last->v.push_back(nod->f[i]);
                q.push(nod->f[i]);
            }
        }
    }
    aux = rad; //aux = nodul din trie pentru caracterul curent din text
    for (int i=0; i<strlen(c); i++){
        while (aux != rad && aux->f[c[i]-'a'] == NULL){
            aux = aux->last;
        }
        if (aux->f[c[i]-'a'] != NULL){
            aux = aux->f[c[i]-'a'];
        }
        aux->sol++;
    }
    dfs(rad);
    for (int i=1; i<=n; i++){
        fout << w[i]->sol << "\n";
    }
    return 0;
}