Cod sursa(job #1994891)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 26 iunie 2017 15:06:05
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <vector>
using namespace std;

#define MAX 1000001

class Set {
public:
	Set() : m{ MAX }, values(MAX, -1), next(MAX, -1)
	{
		for (int i = 0; i < m; ++i)
		{
			values[i] = -1;
			next[i] = -1;
		}
	}
	int d(int i)
	{
		return i % m;
	}
	void add_value(int value)
	{
		if (find_value(value))
			return;
		int poz = d(value);
		if (values[poz] == -1)
		{
			values[poz] = value;
			return;
		}
		do {
			poz = next[poz];
		} while (next[poz] != -1);
		next[poz] = first;
		values[first] = value;
		int aux = first;
		while (values[first] != -1)
			++first;
		next[aux] = first;
	}
	void delete_value(int value)
	{
		int poz = d(value), prec = -1;
		for (int i = 0; i < m && prec == -1; ++i)
			if (next[i] == poz)
				prec = i;
		while (poz != -1 && values[poz] != value)
		{
			prec = poz;
			poz = next[poz];
		}
		if (poz == -1)
			return;
		int urm, anturm;
		while (true)
		{
			urm = next[poz];
			anturm = poz;
			while (urm != -1 && d(values[urm]) != poz)
			{
				anturm = urm;
				urm = next[urm];
			}
			if (urm == -1)
				break;
			values[poz] = values[urm];
			prec = anturm;
			poz = urm;
		}
		if (prec != -1)
			next[prec] = next[poz];
		values[poz] = -1;
		next[poz] = -1;
		if (first > poz)
			first = poz;
	}
	bool find_value(int value)
	{
		int poz = d(value);
		do {
			if (values[poz] == value)
				return true;
			poz = next[poz];
		} while (poz != -1);
		return false;
	}
private:
	int m, first = 0;
	vector<int> values, next;
};

int main()
{
	int op, type, x;
	Set s;

	ifstream is("hashuri.in");
	ofstream os("hashuri.out"); 
	//ifstream is("heapuri.in");
	//ofstream os("heapuri.out");

	is >> op;
	while (op--)
	{
		is >> type >> x;
		switch (type)
		{
		case 1:
			s.add_value(x);
			break;
		case 2:
			s.delete_value(x);
			break;
		default:
			os << s.find_value(x) << "\n";
			break;
		}
	}

	is.close();
	os.close();
	return 0;
}