Cod sursa(job #720862)

Utilizator yamahaFMI Maria Stoica yamaha Data 22 martie 2012 23:31:18
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include <fstream>
#include <cstdlib>
using namespace std;

#define max 1000003
#define prim 670013

//int a, b, N;

int h(int a, int b, int x)
{
    int index;
    index = a*x+b;
    index %= prim;
    index %= max;
    return index;
}

struct nod
{
    int key;
    nod *urm;
};

class lista
{
    nod *vf;
    public:
    lista() {vf=0;}
    int cautare(int);      
    void inserare(int);      
    int sterge(int);
      
} *HT = new lista[prim];

int lista :: sterge(int x)
{
    if(!vf) return 0;
    else if(vf->key == x) // daca e pe prima pozitie 
    {  
       if(vf->urm) { nod *p = vf; vf = vf->urm; p =0; }
       else vf=0; 
       return 1; 
    }
    nod *p = vf;
    nod *q;
    while(p->key!=x && p->urm) { q=p; p=p->urm; }
    if(p->key!=x) return 0; // daca s-a terminat lista
    if(p->urm) q->urm = p->urm;
    else // nodul cu x este ultimul
    q->urm = NULL; 
    p=0;
    return 1;          
}
      
void lista :: inserare(int x)
{
    if(vf)
    {
       nod *p = vf;
       while(p->urm && p->key!=x) p=p->urm;
       if(p->key!=x)
       {
          nod *r = new nod;
          r->key = x;
          r->urm = NULL;
          p->urm = r;
       }
    }
    else
    {
          nod *r = new nod;
          r->key = x;
          r->urm = NULL;
          vf = r;
    }
}
      
int lista :: cautare(int x)
{
    nod *q = vf;
    if(!vf) return 0; // daca lista e goala
    // daca nr nu e in lista
    while(q->key!=x && q->urm) q=q->urm;
    if(q->key==x) return 1; // daca nr e in lista
    return 0;
}
      
int main ()
{
    ifstream f("grader_test10.in");
    ofstream g("hashuri.out");
    
    int a, b, N;
    
    a = rand()%20;
    b = rand()%20+1;
    
    int i, index, t, w, x;
    f>>N; // nr de operatii
    for(i=1;i<=N;++i)
    {
         f>>t>>x;
         index = h(a,b,x); 
         if(t == 1)
              HT[index].inserare(x);
         else if(t == 2)
              HT[index].sterge(x);
         else if(t == 3)
         { 
              w = HT[index].cautare(x); 
              if(w == 1) g<<"1"<<endl;
              else g<<"0"<<endl;
         }
    }
    f.close(); g.close();
    return 0;
}