Pagini recente » Cod sursa (job #1128729) | Cod sursa (job #2500852) | Cod sursa (job #1471109) | Cod sursa (job #2053657) | Cod sursa (job #739626)
Cod sursa(job #739626)
#include <stdio.h>
#include <fstream>
const int M1=1022467;
const int M2=1022449;
using namespace std;
template <class Type>
class hash{
Type *T;
char *nu_exista;
char *folosit;
int f(Type,int);
public:
hash();
~hash();
int query(Type x);
int insereaza(Type x);
int sterge(Type x);
};
template <class Type>
hash<Type>::hash()
{
T=new Type[M1];
nu_exista=new char[M1];
folosit=new char[M1];
for (int i=0;i<M1;i++){
T[i]=0;
nu_exista[i]=0;
folosit[i]=0;
}
}
template <class Type>
hash<Type>::~hash()
{
delete[] T;
delete[] nu_exista;
delete[] folosit;
}
template <class Type>
int hash<Type>::query(Type x)
{
int t;
for(int i=0;;i++){
t=f(x,i);
if (folosit[t]==0) return 0;
if (T[t]==x && !nu_exista[t]) return 1;
}
return 0;
}
template <class Type>
int hash<Type>::insereaza (Type x)
{
int i,temp,j;
for (i=0;temp=f(x,i), folosit[temp]&&(T[temp]!=x||nu_exista[temp])&&(i<M2); i++);
if (T[temp]==x && folosit[temp]) return -1;
for (j=0;folosit[f(x,j)]&&!nu_exista[f(x,j)];j++);
T[f(x,j)]=x;
nu_exista[f(x,j)]=0;
folosit[f(x,j)]=1;
return f(x,j);
}
template <class Type>
int hash<Type>::sterge (Type x)
{
int temp;
for(int i=0;;i++){
temp=f(x,i);
if (!folosit[temp]) return -1;
if (T[temp]==x && !nu_exista[temp]){
nu_exista[temp]=1;
return temp;
}
}
}
template<class Type>
int hash<Type>::f(Type x, int i){
int integer=(int)x;
int fract=int(1000*(x-integer));
return ((((integer+fract)%M1)+i*(1+(integer+fract)%M2))%M1);
}
template<>
int hash<char *>::f(char *str, int i)
{
int x = 5381;
int c;
while ((c = *str++))
x = ((x << 5) + x) + c;
return (((x%M1)+i*(1+x%M2))%M1);
}
int main()
{
int n;
hash< int> has;
int op,nr;
ifstream in ("hashuri.in");
ofstream out ("hashuri.out");
in>>n;
for (register int i=1;i<=n;i++){
in>>op>>nr;
if (op==1){ has.insereaza(nr); continue;}
if (op==2){ has.sterge(nr); continue;}
if (op==3) out<<has.query(nr)<<"\n";
}
return 0;
}