Cod sursa(job #1277572)

Utilizator evodaniVasile Daniel evodani Data 27 noiembrie 2014 20:52:48
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
using namespace std;
FILE *fin, *fout;

#define mod 600011

struct node {
	int val;
	node* next;
};

typedef node* List;

List hashTable[mod];

void listInsert (List &L, List p, int val) { //insert val after p in L
	List aux = new node; aux->val = val;

	if (p) { //insert after p
		aux->next = p->next;
		p->next = aux;
	}
	else { //insert at the beginning of the list
		aux->next = L;
		L = aux;
	}
}

void listErase (List &L, List p) {
	List aux;

	if (p) {
		aux = p->next;
		p->next = aux->next;
		delete aux;
	}
	else {
		aux = L;
		L = L->next;
		delete aux;
	}
}

List inList (List L, int val) {
	List p = L;
	while (p) {
		if (p->val == val) return p;
		else p = p->next;
	}
	return NULL;
}

int hashKey (int val) {
	return val % mod;
}

void addToHash (List* hashTable, int val) {
	int key = hashKey(val);
	List p = hashTable[key], prev = NULL;
	while (p) {
		prev = p;
		p=p->next;
	}

	listInsert (hashTable[key], prev, val);
}

void eraseFromHash (List* hashTable, int val) {
	int key = hashKey(val);
	List p = hashTable[key], prev = NULL;
	while (p->val != val) {
		prev = p;
		p = p->next;
	}
	listErase (hashTable[key], prev);
}

int isInHash (List* hashTable, int val) {
	int key = hashKey (val);
	return (inList(hashTable[key], val)!=NULL);
}

int main() {
	fin = fopen ("hashuri.in", "r");
	fout = fopen ("hashuri.out", "w");

	int n, i, t, val;
	fscanf (fin, "%d", &n);

	for (i=1; i<=n; ++i) {
		fscanf (fin, "%d%d", &t, &val);
		if (t==1) { // se adauga val la multime
			addToHash(hashTable, val);
		} else
		if (t==2) { // se sterge val din multime daca este inclus
			if (isInHash (hashTable, val))
				eraseFromHash(hashTable, val);
		}
		else { // scrie 1 daca val este in multime
			fprintf (fout, "%d\n", isInHash(hashTable, val));
		}
	}

	fclose(fin); fclose(fout);
	return 0;
}