Cod sursa(job #101917)

Utilizator andrei_infoMirestean Andrei andrei_info Data 13 noiembrie 2007 22:03:18
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.15 kb
#include <cstdio>
#include <cstdlib>
#define NR 5000993
#include <string>

using namespace std;

char T[10000000], P[25];
int rez, N, M;
unsigned int put[20];

typedef struct nod {
                unsigned int h;
                int nr;
                nod *next;
                } nod;
nod* hash[NR];

void add(unsigned int h)
{
    int poz = h % NR;
    nod* aux = hash[poz];
    while ( aux != NULL )
    {
        if (aux->h == h )
        {
            aux->nr++;
            return;
        };
        aux = aux->next;

    };
    nod* aux2;
    aux2 = new nod;
    aux2->h=h;
    aux2->nr=1;
    aux2->next= hash[poz];
    hash[poz] = aux2;
};

int query(unsigned int h )
{
    int poz = h % NR;
    for ( nod* aux = hash[poz]; aux != NULL ; aux = aux->next)
        if (aux->h == h )
        {
            int rez = aux->nr;
            aux->nr =0 ;
            return rez;
        };
    return 0;
};

int main()
{
    freopen("abc2.in", "r", stdin);
    freopen("abc2.out", "w", stdout);
    gets(T);
    gets(P);
    //scanf("%s\n", &T);
    //scanf("%s\n", &P);
    N = strlen(T);
    M = strlen(P);
    unsigned int p=0,t=0;
    put[0] = 1;
    for (int i = 1; i<20; i++)
        put[i] = put[i-1] * 3;

    for (int i=0; i<M; i++)
     {
          p = ( 3*p + P[i]-'a'+1);
          t = ( 3*t + T[i]-'a'+1);
     }

     //Q[t]++;
     add(t);
     for (int i=0; i<N-M; i++)
     {
           //t = (d*(t - ((tonum(T[i])*h) % q)) + tonum(T[i+m])) % q;
           t = 3*(t - (T[i]-'a'+1)*( put[M-1] ) ) + T[i+M]-'a'+1;
           if  ( t<0) exit(1);
           //V[t%NR].push_back(i+1);
           //Q[t]++;
           add(t);
     }

     //rez += V[p].size();
     //p%=NR;
     rez+= query(p);
     //Q[p]=0;
     for( gets(P); !feof(stdin); gets(P) )
     {
         p=0;
         for (int i=0; i<M; i++)
               p = ( 3*p + P[i]-'a'+1);
         //rez+=V[p].size();
         if ( p < 0 ) exit(1);
         //rez+=Q[p];
         //Q[p]=0;
         rez+=query(p);
     };

     printf("%d", rez);
     fclose(stdin);
     fclose(stdout);

     return 0;
};