mercredi 28 janvier 2015

Can someone explain this implementation of a hashtable?


This is the problem setter's implementation of a hash table. I am fairly new to hash tables, and the only ones I have seen make use of structures for forming the lists. Can someone explain this implementation, which is given in the editorial, though not explained.


I can't understand how collisions have been taken care of. If possible, please explain the role of vis[], head[] and nextcell[].


http://ift.tt/1BxSJJN



#include<bits/stdc++.h>
using namespace std;

#define MEM(a, b) memset(a, (b), sizeof(a))
#define CLR(a) memset(a, 0, sizeof(a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define ABS(X) ( (X) > 0 ? (X) : ( -(X) ) )
#define S(X) ( (X) * (X) )
#define SZ(V) (int )V.size()
#define FORN(i, n) for(i = 0; i < n; i++)
#define FORAB(i, a, b) for(i = a; i <= b; i++)
#define ALL(V) V.begin(), V.end()
#define IN(A, B, C) ((B) <= (A) && (A) <= (C))

typedef pair<int,int> PII;
typedef pair<double, double> PDD;
typedef vector<int> VI;
typedef vector<PII > VP;

#define AIN(A, B, C) assert(IN(A, B, C))

typedef long long int LL;

char S1[250005], S2[250005];
int len1, len2;

int vis[35000000];
int head[35000000];
int nextCell[35000000];
int info[35000000];
int node;

LL prime2 = 34369934, prime1 = 9584612342;
int mark;
int cnt;

void insert(int hash, int start)
{
if(vis[hash] != mark)
{
vis[hash] = mark;
head[hash] = -1;
}

info[node] = start;
nextCell[node] = head[hash];
head[hash] = node++;
}

int check(int hash, int at, int len)
{
if(vis[hash] != mark) return 0;

int flag, j, i;
for(i = head[hash]; i != -1; i = nextCell[i])
{
int val = info[i];
flag = 1;
for(j = 0; j < len; j++)
{
cnt++;
if(S1[val + j] != S2[at + j])
{
flag = 0;
break;
}
}

if(flag)
return 1;
}

return 0;
}

int possible(int len)
{
mark++;
node = 0;

if(len == 0) return -1;

LL hash = 0, mul = 1;
int i;

for(i = 0; i < len; i++)
{
hash = (hash * prime1 + S1[i]) % prime2;
mul = (mul * prime1) % prime2;
}

mul = (prime2 - mul) % prime2;

insert(hash, 0);
for(; i < len1; i++)
{
hash = (hash * prime1 + S1[i] + mul * S1[i - len]) % prime2;
insert(hash, i - len + 1);
}

hash = 0;
for(i = 0; i < len; i++)
{
hash = (hash * prime1 + S2[i]) % prime2;
}

if(check(hash, 0, len)) return 0;
for(; i < len2; i++)
{
hash = (hash * prime1 + S2[i] + mul * S2[i - len]) % prime2;
if(check(hash, i - len + 1, len)) return i - len + 1;
}

return -1;
}

int main()
{
//Some processing
}




Aucun commentaire:

Enregistrer un commentaire