Cod sursa(job #1413685)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 2 aprilie 2015 00:40:51
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int amax = 1000005;
const int smax = 10005;
const int mmax = 105;

int A, i, j, m, n, l, L, R, sol[mmax];
char a[amax], s[smax];

struct trie
{
    vector<int> v;
    int count;
    trie *f[26];
    trie *fail;

    trie()
    {
        v.resize(0);
        count = 0;
        memset(f, 0, sizeof(f));
        fail = NULL;
    }
};

trie *root = new trie;
trie *q[smax * mmax];
trie *t, *x, *y;

void insert()
{
    t = root;
    for(j = 0; j < n; j++)
    {
        l = s[j] - 'a';

        if(!t->f[l])
            t->f[l] = new trie;

        t = t->f[l];
    }
    t->v.pb(i);
}

void bfs()
{
    root->fail = root;
    L = R = 1;
    q[L] = root;

    while(L <= R)
    {
        x = q[L++];

        for(i = 0; i < 26; i++)
            if(x->f[i] != NULL)
            {
                y = x->f[i];

                t = x->fail;
                while(t != root && t->f[i] == NULL)
                    t = t->fail;

                if(t->f[i] != NULL && t->f[i] != y)
                    t = t->f[i];

                y->fail = t;
                q[++R] = y;
            }
    }
}

int main()
{
    freopen("ahocorasick.in", "r", stdin);
    freopen("ahocorasick.out", "w", stdout);

    scanf("%s", a);
    A = strlen(a);

    scanf("%d", &m);
    for(i = 1; i <= m; i++)
    {
        scanf("%s", s);
        n = strlen(s);
        insert();
    }

    bfs();

    t = root;
    for(i = 0; i < A; i++)
    {
        l = a[i] - 'a';

        while(t != root && t->f[l] == NULL)
            t = t->fail;

        if(t->f[l] != NULL)
            t = t->f[l];

        t->count++;
    }

    for(i = R; i; i--)
    {
        t = q[i];
        t->fail->count += t->count;

        for(auto it : t->v)
            sol[it] = t->count;
    }

    for(i = 1; i <= m; i++)
        printf("%d\n", sol[i]);

    return 0;
}