Cod sursa(job #2295124)

Utilizator miruna1224Floroiu Miruna miruna1224 Data 3 decembrie 2018 10:06:01
Problema Abc2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.89 kb
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>

#define p 5230176601

using namespace std;

//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[22], *text = (char *)malloc(10000001);

    unsigned int hs;

    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--;
    }

    int lcuv = 0;

    while (fgets(cuv, 22, 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));
    }

    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);
    hs = (unsigned int)crt_hash;
    if((dictionar[hs/8] & (1 << hs%8)) != 0)
        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;

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

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

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

    fclose(f);

    free(text);
    free(dictionar);

    return 0;
}