Cod sursa(job #1017883)

Utilizator bghimisFMI Ghimis Bogdan bghimis Data 28 octombrie 2013 16:31:24
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cstdio>
using namespace std;
 
struct nod
{
  int valoare;
  nod *nod_urmator;
};
 
nod* hashu[666013];
 
int hashFunc (int nr)
{
  return nr % 666013;
}
 
int cauta(int n);

void adaugare (int val)
{
  if (cauta(val) == 1)
    return;

  int hash_val = hashFunc(val);
   
  nod *nou = new nod;
  nou->valoare = val;
  nou->nod_urmator = NULL;
 
  nod *cap = hashu[hash_val];
  if (cap == NULL)
    {
      hashu[hash_val] = nou;
 
      return;
    }
 
  while (cap->nod_urmator != NULL)
    cap = cap->nod_urmator;
 
  cap->nod_urmator = nou;
}
 
void stergere (int val)
{
  int hash_val = hashFunc(val);
 
  nod *cap = hashu[hash_val];
  if (cap == NULL)
    return;
 
  if (cap->valoare == val)
    {
      hashu[hash_val] = hashu[hash_val]->nod_urmator;
      return;
    }
 
  nod *anterior = NULL;
  while (cap != NULL)
    {
      if (cap->valoare == val)
    {
      anterior->nod_urmator = cap->nod_urmator;
      delete cap;
      return;
    }
       
      anterior = cap;
      cap = cap->nod_urmator;
    }
}
 
int cauta(int val)
{
  int hash_val = hashFunc(val);
 
  nod *cap = hashu[hash_val];
  if (cap == NULL)
    return 0;
 
  while (cap != NULL)
    {
      if (cap->valoare == val)
    return 1;
      cap = cap->nod_urmator;
    }
 
  return 0;
}
 
/*void afisare (nod* n)
{
  while (n != NULL)
    {
      cout << n->valoare << " ";
      n = n->nod_urmator;
    }
   
  cout << "\n";
}
*/

int main()
{
  FILE *fin, *fout;
  
  fin = fopen( "hashuri.in", "r" );
  int q;

  fscanf( fin, "%d", &q );
  
  fout = fopen( "hashuri.out", "w" );
  while ( q ) {
    int type, val;

    fscanf( fin, "%d%d", &type, &val );
      
    if (type == 1)
      adaugare(val);
    else if (type == 2)
      stergere(val);
        else
	  fprintf( fout, "%d\n", cauta(val) ? 1 : 0 );
    
    --q;
    }
  
  fclose( fin );
  fclose( fout );
  
  return 0;
}