Cod sursa(job #1411974)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 1 aprilie 2015 01:42:39
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.66 kb
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "ahocorasick";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

const int NMAX = 100 + 5;
const int LMAX = 1000000 + 5;
const int CMAX = 10000 + 5;

struct node {
    node *f[26];
    node *fail;
    vector<int> V;
    int nr;

    node() {
        memset(f, 0, sizeof(f));
        fail = 0;
        nr = 0;
    }
};

int N;
char text[LMAX];
node *root;
int I, S;
node *C[CMAX*NMAX];
int sol[NMAX];

void insert(int ind, char *word) {
    int i, c, L = strlen(word);
    node *Q = root;

    for(i = 0; i < L; i++) {
        c = word[i] - 'a';

        if(Q->f[c] == NULL)
            Q->f[c] = new node;

        Q = Q->f[c];
    }

    Q->V.push_back(ind);
}

map<node*, int> M;
int cnt;

void bfs() {
    int i;
    node *Q = root, *P, *cfail;

    root->fail = root;

    I = S = 0;
    C[S++] = root;

    while(I < S) {
        Q = C[I++];

        M[Q] = ++cnt;

        for(i = 0; i < 26; i++) {
            P = Q->f[i];

            if(P == NULL)
                continue;

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

            if(cfail->f[i] != NULL && cfail->f[i] != P)
                cfail = cfail->f[i];

            P->fail = cfail;

            C[S++] = P;
        }
    }
}

void ahocorasick() {
    int i, c, L = strlen(text);
    node *Q = root;

    for(i = 0; i < L; i++) {
        c = text[i] - 'a';

        while(Q != root && Q->f[c] == NULL)
            Q = Q->fail;

        if(Q->f[c] != NULL)
            Q = Q->f[c];

        Q->nr++;
    }
}

void antibfs() {
    int i;
    node *Q, *P;

    for(S--; S >= 0; S--) {
        Q = C[S];

        Q->fail->nr += Q->nr;

        for(auto x : Q->V)
            sol[x] = Q->nr;
    }
}

int main() {
    int i;
    char word[CMAX];

#ifndef ONLINE_JUDGE
    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);
#endif

    scanf("%s", text);
    scanf("%d", &N);

    root = new node;

    for(i = 1; i <= N; i++) {
        scanf("%s", word);
        insert(i, word);
    }

    bfs();
    ahocorasick();
    antibfs();

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

    return 0;
}