Cod sursa(job #1419328)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 15 aprilie 2015 13:22:10
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <stdio.h>
#include <assert.h>

#define MAX_N 1000000
#define MOD 666013
#define NIL -1

typedef struct {
	int v, next;
} hash;

FILE *f, *g;
hash l[MAX_N];    // liste simplu inlantuite alocate static
int lsize;
int h[MOD];       // inceputul listelor alocate static
int st[MAX_N], s; // stiva de pozitii refolosibile

inline int hashFind(int x) {
	int i = h[x - (x / MOD) * MOD];

	while ((i != NIL) && (l[i].v != x)) {
		i = l[i].next;
	}
	return i;
}
inline void hashInsert(int x) {
	int p = s ? st[--s] : lsize++;
	int hash = x - (x / MOD) * MOD;

	l[p].v = x;
	l[p].next = h[hash];
	h[hash] = p;
}
inline void hashExtract(int x) {
	int hash = x - (x / MOD) * MOD;
	int i = h[hash];

	if (l[i].v == x) {
		h[hash] = l[i].next;
		st[s++] = i;
	} else {
		while ((l[i].next != NIL) && (l[l[i].next].v != x)) {
			i = l[i].next;
		}
		if (l[i].next != NIL) {
			st[s++] = l[i].next;
			l[i].next = l[l[i].next].next;
		}
	}
}
inline void hashExist(int x) {
	fputc((hashFind(x) != NIL) + '0', g);
	fputc('\n', g);
}
typedef void(*BranchTable)(int);
BranchTable branchTable[3] = { hashInsert, hashExtract, hashExist };

int main(void) {
	int testNum;
	int x;

	for (int i = 0; i < MOD; i++) {
		h[i] = NIL;
	}

	f = fopen("hashuri.in", "r");
	assert(f != NULL);
	fscanf(f, "%d ", &testNum);
	g = fopen("hashuri.out", "w");
	assert(g != NULL);
	for (; testNum; testNum--) {
		char c = fgetc(f);
		fscanf(f, "%d ", &x);
		branchTable[c - '1'](x);
	}
	fclose(f);
	fclose(g);
	return 0;
}