Pagini recente » Cod sursa (job #2713776) | Cod sursa (job #3039146) | Cod sursa (job #2822952) | Cod sursa (job #1362770) | Cod sursa (job #3135151)
#include <iostream>
#include <fstream>
#include <set>
#include <queue>
#include <cmath>
using namespace std;
ifstream fin("zeap.in");
ofstream fout("zeap.out");
struct Pair
{
int a, b;
Pair(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
Pair& operator=(const Pair& per)
{
if (this != &per)
{
this->a = per.a;
this->b = per.b;
}
return *this;
}
bool operator<(const Pair& per) const
{
return abs(this->a - this->b) < abs(per.a - per.b);
}
bool operator>(const Pair& per) const
{
return abs(this->a - this->b) > abs(per.a - per.b);
}
};
priority_queue<Pair, vector<Pair>, greater<Pair>> pairQueue;
set<int> numSet;
void updatePair(int x)
{
int minimum = 1000000010, number = x;
auto it = numSet.find(x);
if (it != numSet.end())
{
if (it != numSet.begin())
{
auto predecessor = it;
--predecessor;
minimum = abs(x - *predecessor);
number = *predecessor;
}
if (++it != numSet.end())
{
auto successor = it;
if (abs(x - *successor) < minimum)
number = *successor;
}
}
if (number != x)
pairQueue.push(Pair(x, number));
}
void insertNumber(int x)
{
if (!numSet.count(x))
{
numSet.insert(x);
updatePair(x);
}
}
int removeNumber(int x)
{
if (numSet.count(x))
{
auto it = numSet.find(x);
auto predecessor = it;
auto successor = it;
if (it != numSet.begin())
{
auto predecessor = it;
--predecessor;
}
if (++successor != numSet.end())
{
pairQueue.push(Pair(*predecessor, *successor));
}
numSet.erase(x);
return 1;
}
return -1;
}
int searchNumber(int x)
{
return numSet.count(x);
}
int maxDifference()
{
if (numSet.size() < 2)
return -1;
auto minimum = numSet.begin();
auto maximum = numSet.rbegin();
return abs(*minimum - *maximum);
}
int minDifference()
{
if (numSet.size() < 2)
return -1;
Pair x = pairQueue.top();
while (!numSet.count(x.a) || !numSet.count(x.b))
{
pairQueue.pop();
if (numSet.count(x.a))
updatePair(x.a);
else if (numSet.count(x.b))
updatePair(x.b);
x = pairQueue.top();
}
return abs(x.a - x.b);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string command;
int x;
while (fin >> command)
{
if (command == "I")
{
fin >> x;
insertNumber(x);
}
else if (command == "S")
{
fin >> x;
int val = removeNumber(x);
if (val == -1)
fout << -1 << "\n";
}
else if (command == "C")
{
fin >> x;
fout << searchNumber(x) << "\n";
}
else if (command == "MAX")
{
fout << maxDifference() << "\n";
}
else if (command == "MIN")
{
fout << minDifference() << "\n";
}
}
return 0;
}