Cod sursa(job #1987966)

Utilizator ArctopusKacso Peter-Gabor Arctopus Data 1 iunie 2017 18:21:56
Problema Aho-Corasick Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <queue>
#include <climits>
#include <map>
#include <unordered_map>
#include <list>

#define ll long long
#define pb push_back

using namespace std;

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

const int NLIM = 1e6 + 10;

int N;
string str;

vector< int > graph[NLIM];
char nodc[NLIM];
int endc[NLIM];
int nodnr = 1;

int res[NLIM];



int gi;

void add( string& s, int x, int nod )
{
    int found = 0;
    for( int j = 0; j < graph[nod].size() && !found; ++j )
    {
        int nnod = graph[nod][j];
        if( nodc[nnod] == s[x] )
            found = nnod;
    }

    if( found )
    {
        if( x >= s.size() - 1 )
        {
            endc[found] = gi;
            return;
        }

        add( s, x + 1, found );
    }
    else
    {
        ++nodnr;
        graph[nod].pb( nodnr );
        nodc[nodnr] = s[x];

        if( x >= s.size() - 1 )
        {
            endc[nodnr] = gi;
            return;
        }
        add( s, x +  1, nodnr );
    }
}

int main()
{
    fin >> str;
    fin >> N;
    for( gi = 1; gi <= N; ++gi )
    {
        string s;
        fin >> s;
        add( s, 0, 1 );
    }

    queue< int > from;
    queue< int > to;


    for( int i = 0; i < str.size(); ++i )
    {
        from.push( 1 );
        while( from.size() )
        {
            int nod = from.front();


            for( int j = 0; j < graph[nod].size(); ++j )
            {
                int nnod = graph[nod][j];
                if( nodc[nnod] == str[i] )
                {
                    to.push( nnod );
                    ++res[endc[nnod]];
                }
            }
            from.pop();
        }

        swap( from, to );
    }

    for( int i = 1; i <= N; ++i )
        fout << res[i] << "\n";

    return 0;
}