Cod sursa(job #29451)

Utilizator gigi_becaliGigi Becali gigi_becali Data 9 martie 2007 14:03:57
Problema Jocul Flip Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.42 kb
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#define maxn 997
#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);
	insert(765);
	insert(123435);
	printf("%d\n", find(123435));
	printf("%d\n", find(123454));
	printf("%d\n", find(765));
	printf("%d\n", find(766));

	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(555555);//, erase(i+j);
	
	return 0;
}