Pagini recente » Cod sursa (job #2645189) | Cod sursa (job #2720715) | Cod sursa (job #812542) | Cod sursa (job #1124693) | Cod sursa (job #2295036)
#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], *text = (char *)malloc(10000001);
unsigned int hs;
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--;
}
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);
hs = hashString(cuv);
dictionar[hs/8] = dictionar[hs/8] | (1 << (hs % 8));
}
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);
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);
t = clock() - t;
printf("\nTimp de executare = %.6f\n", t/CLOCKS_PER_SEC);
return 0;
}