Cod sursa(job #1017849)

Utilizator bghimisFMI Ghimis Bogdan bghimis Data 28 octombrie 2013 15:52:59
Problema Hashuri Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin("hashuri.in");
ofstream cout("hashuri.out");

struct nod 
{
  int valoare;
  nod *nod_urmator;
};

vector <nod*> hashu(2000007);

int hashFunc (int nr)
{
  return nr % 2000007;
}

void adaugare (int val)
{
  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()
{
  int n; cin >> n;
  for (int i = 1; i <= n; i++)
    {
      int tipOp, val;
      cin >> tipOp >> val;

      if (tipOp == 1)
	adaugare (val);
      if (tipOp == 2)
	stergere (val);
      if (tipOp == 3)
	cout << cauta(val) << endl;
    }

  cin.close();
  cout.close();

  return 0;
}