Pagini recente » Cod sursa (job #1283164) | Cod sursa (job #15992) | Cod sursa (job #2213956) | Cod sursa (job #1448683) | Cod sursa (job #734040)
Cod sursa(job #734040)
#include<cstdlib>
#include<cstring>
#include<fstream>
using namespace std;
#define max 1000003
#define prim 670013
template <class T> class Hash
{
typedef struct nod
{
T info;
nod* back;
nod* next;
}NOD;
typedef NOD *node;
node *v,p,r;
int a, b;
public:
Hash();
bool random();
inline int h(const int&);
inline int h(const double&);
inline int h(char*);
bool cautare(const T&);
bool inserare(const T&);
bool sterge(const T&);
~Hash();
};
template <class T> Hash<T>::Hash()
{
v=new node[prim];
for(int i=0;i<prim;i++)
v[i]=NULL;
}
template <class T> bool Hash<T> :: random()
{
srand( 13 );
a = rand()%20;
srand( 1 );
b = rand()%20+1;
}
template <class T> inline int Hash<T> :: h(const int &x)
{
int index;
index = a*x+b;
index %= prim;
return index%max;
}
template <class T> inline int Hash<T> :: h(const double &x)
{
int index = (int) x;
index = (int)(index + 1000* (x - index) );
index = a*index + b;
index %= prim;
return index%max;
}
template <class T> inline int Hash<T> :: h(char *x)
{
int index = 0, n = strlen(x);
for(int i = 0; i < n; i++) index ^= (index<<5) + (index>>2) + x[i];
index = a*index + b;
index %= prim;
return index%max;
}
template <class T> bool Hash<T> :: cautare(const T& value)
{
register int x,k=0;
x=h(value);
p=v[x];
while(p!=NULL&&k==0)
{
if(p->info==value)
k=1;
r=p;
p=p->next;
}
return k;
}
template <class T> bool Hash<T> :: inserare(const T& value)
{
register int x=h(value);
p=v[x];
if(cautare(value)==0)
{
if(v[x]==NULL)
{
v[x]=new NOD;
v[x]->info=value;
v[x]->next=NULL;
v[x]->back=NULL;
}
else
{
p=v[x];
while(p->next!=NULL)
p=p->next;
r=new NOD;
r->info=value;
r->next=NULL;
r->back=p;
p->next=r;
}
return 1;
}
return 0;
}
template <class T> bool Hash<T> :: sterge(const T& value)
{
register int x=h(value);
p=v[x];
if(cautare(value)==1)
{
if(r==v[x])
{
node s;
s=v[x];
v[x]=v[x]->next;
if(v[x]!=NULL)
v[x]->back=NULL;
delete s;
}
else
{
p=r->back;
p->next=r->next;
if(r->next!=NULL)
r->next->back=p;
delete r;
}
return 1;
}
return 0;
}
template <class T> Hash<T> :: ~Hash()
{
delete [] v;
}
int main ()
{
ifstream f("grader_test1.in");
ofstream g("hashuri.out");
Hash <int> H;
H.random();
register int N, i, index, t, w, x;
f>>N;
for(i=1;i<=N;++i)
{
f>>t>>x;
if(t == 1)
H.inserare(x);
else if(t == 2)
H.sterge(x);
else if(t == 3)
{
g<<H.cautare(x)<<endl;
}
}
f.close(); g.close();
return 0;
}