Cod sursa(job #2791383)

Utilizator cezar_titianuTitianu Cezar cezar_titianu Data 30 octombrie 2021 13:46:29
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>

#define MOD 1000000

template <class from> class hashtable {
private:
	std::vector <from> vec[MOD];
	int hash(from key) {
		unsigned char* byte = reinterpret_cast<unsigned char*>(&key);
		int ans = 0;
		int put = 1;
		for (int index = 0; index < sizeof(key); index++) {
			ans += put * (*byte);
			ans %= MOD;
			put *= 256;
			put %= MOD;
			byte++;
		}
		return ans;
	}
	int search(from val, int pos) {
		for (int index = 0; index < vec[pos].size(); index++) {
			if (vec[pos][index] == val) {
				return index;
			}
		}
		return -1;
	}
public:
	void insert(from val) {
		int pos = hash(val);
		if (search(val, pos) == -1) {
			vec[pos].push_back(val);
		}
	}
	void erase(from val) {
		int pos = hash(val);
		int pos2 = search(val, pos);
		if (pos2 != -1) {
			if (pos2 != vec[pos].size() - 1) {
				vec[pos][pos2] = vec[pos].back();
			}
			vec[pos].pop_back();
		}
	}

	bool check(from val) {
		return (search(val, hash(val)) != -1);
	}
};

hashtable <int> set;

int main() {
	std::ifstream fin("hashuri.in");
	std::ofstream fout("hashuri.out");
	int nrn, cer, val;
	fin >> nrn;
	for (int index = 0; index < nrn; index++) {
		fin >> cer >> val;
		if (cer == 1) {
			set.insert(val);
		}
		else if (cer == 2) {
			set.erase(val);
		}
		else {
			fout << set.check(val) << '\n';
		}
	}
}