Cod sursa(job #1444625)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 30 mai 2015 00:13:07
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
/**
  *  Worg
  */
#include <cstdio>
#include <vector>
#include <cstring>

#define sigma 54
#define DIM (1 << 17) + 10

using namespace std;
FILE *fin=freopen("seti.in","r",stdin);
FILE *fout=freopen("seti.out","w",stdout);

char S[DIM], aux[DIM];
int n, m, len;

void Read_Text()
{
    scanf("%d ", &n);
    for(int i = 1; i <= n; ++i)
    {
        gets(aux);
        strcat(S, aux);
    }
    len = n * 64;
}

struct Trie
            {
                Trie *fiu[sigma];
                int cnt;
                //vector<int>

                Trie()
                {
                    cnt = 0;
                    memset(fiu, 0, sizeof(fiu));
                }
            };

Trie *T = new Trie;

int val(char c)
{
    if( c < 'a' )
        return c - 'A';
    else
        return 26 + c - 'a';
}

void ins(Trie *nod, char *s, int k)     // we modify the insertion of an element in the trie
                                        // because we don't want to insert more than 17 characters
{
    nod -> cnt ++;
    if( k == 17 )
    {
        return;
    }

    int nr = val(*s);

    if( !nod -> fiu[ nr ] )
    {
        nod -> fiu[ nr ] = new Trie;
    }

    ins( nod -> fiu[ nr ], s + 1, k + 1 );
}

void Construct_Trie()                   // build the trie
{
    int i;
    for(i = 0; i < len - 17 + 1; ++i)
    {
        ins(T, S + i, 0);
    }
    for(; i <= len; ++i)
    {
        ins(T, S + i, i - (len - 18 + 1));
    }
}

int Count(Trie *nod, char *s)
{
    if( *s == '\n' )
        return nod -> cnt;

    int nr = val(*s);

    if( nod -> fiu[ nr ] )
        return Count( nod -> fiu[ nr ], s + 1 );
    return 0;
}

void Query()
{
    fgets(aux, 20, stdin);
    printf("%d\n", Count(T, aux));
}

int main()
{
    Read_Text();
    Construct_Trie();
    for(scanf("%d ", &m); m; --m)
        Query();
}