Cod sursa(job #1568079)

Utilizator space.foldingAdrian Soucup space.folding Data 13 ianuarie 2016 21:48:15
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
struct HT {
	struct E {
		int Key;
		bool T;
		int V;
		E() : T(true) {}
	};
	std::vector<E> _table;
	unsigned int _mask;

	HT(unsigned int N) {
		unsigned int n = N;
		while (n & (n + 1)) {
			n |= (n + 1);
		}
		// Make it bigger for sparser collisions
		// minimum 65k elements will need to 255k buckets
		// with 90% access of first time hash, 99% second next bucket...
		n |= (n + 1);
		_table.resize(size_t(n) + 1);
		_mask = n;
	}
	inline unsigned int hash(unsigned long long h) {
		h ^= h >> 33;
		h *= 0xff51afd7ed558ccdLL;
		h ^= h >> 33;
		h *= 0xc4ceb9fe1a85ec53LL;
		h ^= h >> 33;
		return h;
	}

	bool find(int key) {
		auto h = hash(key);

		while (true) {
			h = h & _mask;
			if (_table[h].T) {
				return false;
			}
			else if (_table[h].Key == key) {
				return true;
			}
			h++;
		}
	}

	void insert(int key) {
		auto h = hash(key);

		while (true) {
			h = h & _mask;
			if (_table[h].T) {
				_table[h].T = false;
				_table[h].Key = key;
				return;
			}
			else if (_table[h].Key == key) {
				// Double insert
				return;
			}
			h++;
		}
	}

	void remove(int key) {
		auto h = hash(key);
		while (true) {
			h = h & _mask;
			if (_table[h].T) {
				// Not found
				return;
			}
			else if (_table[h].Key == key) {
				_table[h].T = true;
				return;
			}
			h++;
		}
	}
};

int main() {

	string input;

	ifstream fin("hashuri.in");
	getline(fin, input, '\0');
	istringstream sin(input);
	ostringstream sout;
	int n;
	sin >> n;

	HT ht(n);

	for (int i = 0; i < n; i++) {
		int op, c;
		sin >> op >> c;

		if (op == 1) {
			ht.insert(c);
		}
		else if (op == 2) {
			ht.remove(c);			
		}
		else if (op == 3) {
			if (ht.find(c))
				sout << "1\n";
			else
				sout << "0\n";
		}
	}
	ofstream fout("hashuri.out", ios::binary);
	fout << sout.str();
	return 0;
}