Cod sursa(job #1557969)

Utilizator Theodor1000Cristea Theodor Stefan Theodor1000 Data 28 decembrie 2015 15:13:15
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <algorithm>
#include <string>

using namespace std;

struct trie
{
    int val;
    trie *nxt[32], *phi;

    trie ()
    {
        val = 0;
        phi = NULL;
        for (int i = 0; i < 26; ++i)
            nxt[i] = NULL;
    }
} *p, *v, *cap[128], *q[1000010];

string ss, cuv;

inline trie *add (trie *p, int k)
{
    if (k == cuv.size ()) return p;

    if (p -> nxt[cuv[k] - 'a'] == NULL)
        p -> nxt[cuv[k] - 'a'] = new trie;

    return add (p -> nxt[cuv[k] - 'a'], k + 1);
}

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

    fin >> ss;

    int n;
    fin >> n;

    p = new trie;
    for (int i = 1; i <= n; ++i)
    {
        fin >> cuv;
        cap[i] = add (p, 0);
    }

    int st = 2, dr = 1;
    q[1] = p;
    for (int i = 0; i < 26; ++i)
        if (p -> nxt[i] != NULL)
        {
            p -> nxt[i] -> phi = p;
            q[++dr] = p -> nxt[i];
        }

    while (st <= dr)
    {
        for (int i = 0; i < 26; ++i)
            if (q[st] -> nxt[i] != NULL)
            {
                v = q[st] -> phi;
                while (v != p && v -> nxt[i] == NULL)
                    v = v -> phi;

                if (v -> nxt[i] != NULL) q[st] -> nxt[i] -> phi = v -> nxt[i];
                else q[st] -> nxt[i] -> phi = p;

                q[++dr] = q[st] -> nxt[i];
            }

        ++st;
    }

    v = p;
    for (int i = 0; i < ss.size (); ++i)
    {
        while (v != p && v -> nxt[ss[i] - 'a'] == NULL)
            v = v -> phi;

        if (v -> nxt[ss[i] - 'a'] != NULL) v = v -> nxt[ss[i] - 'a'];
        ++(v -> val);
    }

    for (int i = dr; i > 1; --i)
        q[i] -> phi -> val += q[i] -> val;

    for (int i = 1; i <= n; ++i)
        fout << cap[i] -> val << '\n';

    return 0;
}