Cod sursa(job #2750537)

Utilizator vali_27Bojici Valentin vali_27 Data 11 mai 2021 19:57:14
Problema Zeap Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.52 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <set>
#include <queue>
#include <string>

FILE* fin = fopen("zeap.in", "r");
FILE* fout = fopen("zeap.out", "w");

struct Info {
	// unul e nr
	// celalat e predecesorul sau succesorul
	// dar mereu x < y
	int x, y;
};

struct Compare {
	bool operator()(const Info& i1, const Info& i2)
	{
		return i1.y - i1.x > i2.y - i2.x;
	}
};

std::unordered_map<int, bool> map;
std::priority_queue<Info, std::vector<Info>, Compare> heap;
std::set<int> set;

inline std::pair<int,int> getPredAndSucc(const std::set<int>& s, int x)
{
	int pred =-1, succ = -1;

	auto it = s.find(x);

	if (it != s.begin())
	{
		pred = *std::prev(it);
	}
	
	++it;
	if (it != s.end())
	{
		succ = *it;
	}

	return { pred,succ };

}

inline void Insert(int x)
{
	if (map[x] == false)
	{
		map[x] = true;
		set.insert(x);
	}
	auto pred_succ = getPredAndSucc(set, x);
	if (pred_succ.first != -1)
		heap.push({ pred_succ.first, x });

	if (pred_succ.second != -1)
		heap.push({ x,pred_succ.second });
}

inline void Delete(int x)
{
	if (map[x] == false)
	{
		fputs("-1\n", fout);
		return;
	}
	map[x] = false;
	auto pred_succ = getPredAndSucc(set, x);

	set.erase(x);

	// nu sterg si din heap, fac un lazy delete
	// sterg din heap cand trebuie sa afisez din heap ceva
	// in schimb daca am nr:  a b c  si sterg b-ul atunci in heap 
	// trebuie sa bag c - a pt ca nu aveam informatia asta de dinainte
	if (pred_succ.first != -1 && pred_succ.second != -1)
		heap.push({ pred_succ.first, pred_succ.second });
}

inline bool Search(int x)
{
	return map[x];
}

inline int MaxDif()
{
	if (set.size() > 1)
		return *set.rbegin() - *set.begin();
	return -1;
}

inline int MinDif()
{	
	while (heap.size() && (map[heap.top().x] == false || map[heap.top().y] == false))
	{
		heap.pop();
	}
	if (heap.empty())return -1;

	return heap.top().y - heap.top().x;
}
 
int main()
{
	char input[20];
	while (fgets(input, 20, fin) != NULL)
	{
		if (input[0] == 'I')
			Insert(std::stoi(input + 2));
		else if (input[0] == 'S')
			Delete(std::stoi(input + 2));
		else if (input[0] == 'C')
		{
			fputs(std::to_string(Search(std::stoi(input + 2))).c_str(), fout);
			fputs("\n", fout);
		}
		else if (input[1] == 'A')
		{
			fputs(std::to_string(MaxDif()).c_str(), fout);
			fputs("\n", fout);
		}
		else if (input[1] == 'I')
		{
			fputs(std::to_string(MinDif()).c_str(), fout);
			fputs("\n", fout);
		}
	}
}