Cod sursa(job #2292968)

Utilizator miruna1224Floroiu Miruna miruna1224 Data 30 noiembrie 2018 12:46:03
Problema Abc2 Scor 0
Compilator c-64 Status done
Runda Arhiva de probleme Marime 2.66 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

const int p = 10003;

typedef struct nod
{
    struct nod *next;
    unsigned long long info;
} Nod;

int convert( char *s)
{
    unsigned long long hh = 0 , pp = 1;
    int i ;
    for ( i = strlen(s) ; i >= 0; i-- )
    {
        hh = hh + pp * (s[i]- '0');
        pp *= 3;
    }
    return (int)(hh%p);
}

int h ( int x)
{
    return x % p;
}

Nod** alocare()
{
    Nod **v;
    v = (Nod**) calloc( p, sizeof(Nod*));
    return v;
}


void inserare ( Nod** v, unsigned long long x )
{
    Nod *prim ;
    int poz = h(x);

    for(prim = v[poz]; prim != NULL; prim = prim->next)
    {
        if ( prim ->info == x)
            return;
    }
    Nod *aux = (Nod*) malloc ( sizeof(Nod));
    aux->next = NULL;
    aux->info = x;
    if( v[poz] == NULL )
        v[poz] = aux;
    else
    {
        aux->next = v[poz] ->next;
        v[poz]->next = aux;
    }
}

_Bool cautare( Nod** v, int x)
{
    Nod * prim ;
    int poz = h(x);
    for(prim =  v[poz]; prim != NULL; prim = prim->next)
    {
        if ( prim ->info == x)
            return true;
    }
    return false;

}

void dealloc ( Nod*** v)
{
    int i;
    for (i = 0; i < p; i++)
    {
        Nod* prim = *(*v+i);
        for(; prim != NULL;)
        {
            Nod* aux = prim;
            prim = prim->next;
            free(aux);
        }
    }
    free(*v);
}

int main()
{
    FILE *cfile = fopen( "abc2.in " , "r");
    FILE *sfile = fopen ( "abc2.out", "w");

    int nr, ch, i, lcuv = 0;
    Nod **v;
    char cuv[21] ;

    v = alocare();

    do
    {
        ch = fgetc(cfile);
    }
    while ( ch != '\n' );

    fgets(cuv, 21, cfile);
    if(cuv[strlen(cuv)-1] == '\n')
        cuv[strlen(cuv)-1] = '\0';
    lcuv = strlen(cuv);

    inserare( v, convert(cuv));
    while (fgets(cuv, 21, cfile) != NULL)
    {
        if(cuv[strlen(cuv)-1] == '\n')
            cuv[strlen(cuv)-1] = '\0';
        inserare( v , convert(cuv) );
    }

    rewind(cfile);

    i = nr = 0;
    do
    {
        ch = fgetc(cfile);
        if ( ch == '\n')
            break;
        cuv[i++] = ch;
        if ( i  == lcuv)
        {
            cuv[i] = '\0';
            //printf("%s\n", cuv);
            if( cautare(v,convert(cuv)))
                nr++;
            strcpy( cuv, cuv+1);
            cuv[strlen(cuv)-1] = ch;
            cuv[strlen(cuv)] = '\0';
            i --;
        }

    }
    while ( 1);

    fprintf( sfile,"%d", nr);

    fclose(cfile);
    fclose(sfile);

    dealloc (&v);

    return 0;
}