Pagini recente » Borderou de evaluare (job #1036277) | Cod sursa (job #1755544) | Cod sursa (job #1448844) | Cod sursa (job #3211079) | Cod sursa (job #837331)
Cod sursa(job #837331)
#include <fstream>
#include <queue>
#include <set>
using namespace std;
const int inf = 0x3f3f3f3f;
struct MinHeap{
priority_queue<int, vector<int>, greater<int> > H, D;
void push(int x){
H.push(x);
}
void pop(int x){
D.push(x);
}
int top(){
while (!H.empty() && !D.empty() && H.top() == D.top()){
H.pop();
D.pop();
}
if (H.empty())
return -1;
return H.top();
}
};
struct Zeap{
set<int> S;
MinHeap H;
int size;
inline set<int> :: iterator bf(set<int> :: iterator it){
if (it != S.begin())
--it;
return it;
}
inline int max(){
return *bf(S.end());
}
inline int min(){
return *S.begin();
}
void insert(int x){
if (S.find(x) != S.end())
return;
int st = *bf(S.lower_bound(x));
int dr = *S.upper_bound(x);
if (st && st < x)
H.push(x - st);
if (dr && x < dr)
H.push(dr - x);
if (st < x && x < dr)
H.pop(dr - st);
S.insert(x);
++size;
}
bool erase(int x){
set<int> :: iterator it = S.find(x);
if (it == S.end())
return false;
S.erase(*it);
int st = *bf(S.lower_bound(x));
int dr = *S.upper_bound(x);
if (st && st < x)
H.pop(x - st);
if (dr && x < dr)
H.pop(dr - x);
if (st < x && x < dr)
H.push(dr - st);
--size;
return true;
}
bool find(int x){
return S.find(x) != S.end();
}
int smin(){
if (size < 2)
return -1;
return H.top();
}
int smax(){
if (size < 2)
return -1;
return max() - min();
}
};
Zeap Z;
char s[101];
ifstream in("zeap.in");
ofstream out("zeap.out");
int main(){
int x;
while (in >> s){
if (s[0] == 'I'){
in >> x;
Z.insert(x);
continue;
}
if (s[0] == 'S'){
in >> x;
if (!Z.erase(x))
out << "-1\n";
continue;
}
if (s[0] == 'C'){
in >> x;
out << Z.find(x) << "\n";
continue;
}
if (s[1] == 'I')
out << Z.smin() << "\n";
else
out << Z.smax() << "\n";
}
return 0;
}