Pagini recente » Cod sursa (job #1143703) | Cod sursa (job #707145) | Cod sursa (job #706932) | Cod sursa (job #2720715) | Cod sursa (job #29436)
Cod sursa(job #29436)
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#define maxn 1024
#define Mhash 997
int *H[maxn];
int r;
void init_hash()
{
time_t s;
time(&s);
srand(s%997);
for(int i=0;i<maxn;i++) H[i]=new int[0], H[i][0]=0;
r=rand()%47+1;
}
int hash_function(int val)
{
//return (val%Mhash+r*(1+val%(Mhash-7)))%maxn;
return val%maxn;
}
void insert(int val)
{
int poz=hash_function(val);
H[poz][0]++;
H[poz]=(int*)realloc(H[poz], sizeof(int)*(H[poz][0]+1));
H[poz][H[poz][0]]=val;
}
int find(int val)
{
int poz=hash_function(val);
for(int i=1;i<=H[poz][0];i++)
if(H[poz][i]==val) return 1;
return 0;
}
int erase(int val)
{
int poz=hash_function(val);
int i, p=-1;
for(i=1;i<=H[poz][0];i++)
if(H[poz][i]==val) {p=i;break;}
if(p==-1) return 0;
for(i=p+1;i<=H[poz][0];i++) H[poz][i-1]=H[poz][i];
H[poz][0]--;
H[poz]=(int*)realloc(H[poz], sizeof(int)*(H[poz][0]+1));
return 1;
}
int main()
{
init_hash();
insert(34);
insert(23);
printf("%d\n", find(34));
printf("%d\n", find(35));
printf("%d\n", find(23));
erase(34);
for(int i=1;i<=500;i++)
for(int j=1;j<=500;j++) insert(i+j);
for(int i=1;i<=500;i++)
for(int j=1;j<=500;j++) find(i+j), erase(i+j);
return 0;
}