Cod sursa(job #1509004)

Utilizator retrogradLucian Bicsi retrograd Data 23 octombrie 2015 13:33:52
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <iostream>
#include <cassert>
#include <vector>

using namespace std;

int Vec[1000005], Next[1000005], nodesx;

struct Node {
    int cnt, leg[27], bad, adj, parent, c;
} T[1000005];
int root = 1, nodes = 1;

int Where[105];
char Tx[1000005], P[10005];

void addEdge(int a, int b) {
    ++nodesx;
    Vec[nodesx] = b;
    Next[nodesx] = T[a].adj;
    T[a].adj = nodesx;
}

int addWord(char str[]) {
    int node = root;
    for(int i=0; str[i]; i++) {
        int c = str[i] - 'a';

        if(T[node].leg[c] == 0) {
            T[node].leg[c] = ++nodes;
            T[nodes].parent = node;
            T[nodes].c = c;
        }
        node = T[node].leg[c];
    }

    return node;
}

int Q[1000005], b, e;
void build_bad() {

    Q[e++] = root;
    while(b < e) {
        int node = Q[b++];

        if(node != root) {
            int bad = T[T[node].parent].bad;
            int c = T[node].c;

            while(bad && T[bad].leg[c] == 0) bad = T[bad].bad;
            T[node].bad = (bad) ? T[bad].leg[c] : root;
            addEdge(T[node].bad, node);
        }

        for(int c=0; c<='z'-'a'; c++)
            if(T[node].leg[c])
                Q[e++] = T[node].leg[c];
    }
}

void solve(char str[]) {
    int node = root;

    for(int i=0; str[i]; i++) {
        int c = str[i] - 'a';

        while(node && T[node].leg[c] == 0) node = T[node].bad;
        node = (node) ? T[node].leg[c] : root;

        T[node].cnt += 1;
    }
}

void dfs(int node) {
    for(int i = T[node].adj; i; i = Next[i])
        dfs(Vec[i]), T[node].cnt += T[Vec[i]].cnt;
}


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

    int n;

    fin>>Tx>>n;
    for(int i=1; i<=n; i++) {
        fin>>P;
        Where[i] = addWord(P);
    }

    build_bad();
    solve(Tx);
    dfs(root);

    for(int i=1; i<=n; i++) {
        fout<<T[Where[i]].cnt<<'\n';
    }
}