Pagini recente » Istoria paginii utilizator/cristina-alina | Istoria paginii runda/a_a_a | Profil M@2Te4i | Rating orban dan-razvan (odr11) | Cod sursa (job #2294232)
#include <cstring>
#include <cstdio>
#include <unordered_set>
#include <iterator>
#include <cstdlib>
#include <ctime>
using namespace std;
const unsigned int p = 1000000009;
//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]-'0' + 1)) % p;
// p3 = (p3*3) % p;
// }
// return (unsigned int)hh;
//}
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));
}
// unordered_set<unsigned int> :: iterator itr;
// for (itr = dictionar.begin(); itr != dictionar.end(); itr++)
// printf("%u\n", *itr);
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 - (cuv[0] - 'a' + 1) * p3;
strncpy(cuv, text + i, lcuv);
cuv[lcuv] = '\0';
crt_hash = 3 * crt_hash;
crt_hash = (crt_hash + cuv[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;
}