Cod sursa(job #2294955)

Utilizator gigelmargelgigel margel gigelmargel Data 2 decembrie 2018 23:11:55
Problema Abc2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2 kb
#include <cstring>
#include <cstdio>
#include <unordered_set>
#include <iterator>
#include <cstdlib>
#include <ctime>

using namespace std;

//const unsigned int p = 1000000009;

const unsigned int p = 104395303;

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()
{
    unordered_set <unsigned int> dictionar;

    char cuv[23], *text;

    double t = clock();

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

    text = (char *)malloc(10000001);

    fgets(text, 10000001, f);

    int ltext = strlen(text);

    if(text[strlen(text) - 1] == '\n')
    {
        text[strlen(text) - 1] = '\0';
        ltext--;
    }

    int 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);

        dictionar.insert(hashString(cuv));
    }

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

    fclose(f);

    int nr = 0;

    strncpy(cuv, text, lcuv);
    cuv[lcuv] = '\0';

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

    unsigned long long int crt_hash = hashString(cuv);
    if(dictionar.find((unsigned int)crt_hash) != dictionar.end())
        nr++;

    for(int i = 1; i <= ltext - lcuv; i++)
    {
        crt_hash = crt_hash - (text[i-1] - 'a' + 1) * p3;
        crt_hash = 3 * crt_hash;
        crt_hash = (crt_hash + text[i + lcuv-1] - 'a' + 1) % p;

        if(dictionar.find((unsigned int)(crt_hash)) != dictionar.end())
            nr++;
    }

    free(text);

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

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

    fclose(f);

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

    return 0;
}