Cod sursa(job #2295049)

Utilizator gigelmargelgigel margel gigelmargel Data 3 decembrie 2018 00:35:50
Problema Abc2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.25 kb
#include <cstring>
#include <cstdio>
#include <unordered_set>
#include <iterator>
#include <cstdlib>
#include <ctime>

using namespace std;

//const unsigned int p = 1000000009;

const unsigned long long int p = 5230176601;

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

int main()
{
    unsigned char *dictionar = (unsigned char *)calloc(p/8 + 1, 1);

    char cuv[23];

    int ch;

    unsigned int hs, ltext, lcuv;

    double t = clock();

    FILE *f = fopen("abc2.in", "r");

//    fgets(text, 10000001, f);
//
//    int ltext = strlen(text);
//
//    if(text[strlen(text) - 1] == '\n')
//    {
//        text[strlen(text) - 1] = '\0';
//        ltext--;
//    }
//
    ltext = 0;
    while((ch = getc(f)) != '\n')
        ltext++;

    lcuv = 0;
    while (fgets(cuv, 23, f) != NULL)
    {
        if(cuv[strlen(cuv) - 1] == '\n')
            cuv[strlen(cuv) - 1] = '\0';

        if(lcuv == 0)
            lcuv = strlen(cuv);

        hs = hashString(cuv);
        dictionar[hs/8] = dictionar[hs/8] | (1 << (hs % 8));
    }

    rewind(f);

    int nr = 0;

    fgets(cuv, lcuv + 1, f);
    cuv[lcuv] = '\0';

    unsigned long long int p3 = 1;
    for(unsigned int i = 0; i < lcuv - 1; i++)
        p3 = 3 * p3;

    unsigned long long int crt_hash = hashString(cuv);
    hs = (unsigned int)crt_hash;
    if((dictionar[hs/8] & (1 << hs%8)) != 0)
        nr++;

    for(unsigned int i = 1; i <= ltext - lcuv; i++)
    {
        ch = getc(f);

        crt_hash = crt_hash - (cuv[0] - 'a' + 1) * p3;

        //strcpy(cuv, cuv+1);
        cuv[lcuv-1] = ch;
        cuv[lcuv] = '\0';

        crt_hash = 3 * crt_hash;
        crt_hash = (crt_hash + ch - 'a' + 1) % p;

        hs = (unsigned int)crt_hash;
        if((dictionar[hs/8] & (1 << hs%8)) != 0)
            nr++;
    }

    fclose(f);

    f = fopen("abc2.out", "w");

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

    fclose(f);

    free(dictionar);

    t = clock() - t;
    printf("\nTimp de executare = %.6f\n", t/CLOCKS_PER_SEC);

    return 0;
}