Cod sursa(job #1336047)

Utilizator nicol.bolasNicol Bolas nicol.bolas Data 6 februarie 2015 14:29:30
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
#define NMAX 1000005
#define CUVMAX 10005
ifstream fin("ahocorasick.in");
ofstream fout("ahocorasick.out");
struct trie
{
    int sol;
    trie *back;
    trie *f[26];
    vector <trie *> v;
    trie()
    {
        sol=0;
        back=0;
        for (int i=0;i<26;++i)
            f[i]=0;
        v.clear();
    }
} *root,*aux,*nod,*w[105];
queue <trie *> q;
char a[NMAX],str[CUVMAX],*p;
int n;
trie *adauga(trie *r, char *s)
{
    if (*s==0)
        return r;
    if (r->f[*s-'a']==NULL)
        r->f[*s-'a']=new trie;
    return adauga(r->f[*s-'a'],s+1);
}
void bfs()
{
    int i;
    q.push(root);
    while (!q.empty())
    {
        nod=q.front(); q.pop();
        for (i=0;i<26;++i)
            if (nod->f[i])
            {
                aux=nod->back;
                while (aux!=NULL && aux!=root && aux->f[i]==NULL)
                    aux=aux->back;
                if (aux!=NULL && aux->f[i])
                    nod->f[i]->back=aux->f[i];
                else
                    nod->f[i]->back=root;
                nod->f[i]->back->v.push_back(nod->f[i]);
                q.push(nod->f[i]);
            }
    }
}
void dfs(trie *nod)
{
    int i;
    for (i=0;i<nod->v.size();++i)
    {
        dfs(nod->v[i]);
        nod->sol+=nod->v[i]->sol;
    }
}
int main()
{
    int i;
    fin>>a>>n;
    root=new trie;
    for (i=1;i<=n;++i)
    {
        fin>>str;
        w[i]=adauga(root,str);
    }
    bfs();
    aux=root;
    for (p=a;*p;++p)
    {
        while (aux!=root && aux->f[*p-'a']==NULL)
            aux=aux->back;
        if (aux->f[*p-'a'])
            aux=aux->f[*p-'a'], aux->sol++;
    }
    dfs(root);
    for (i=1;i<=n;++i)
        fout<<w[i]->sol<<"\n";
    return 0;
}