Pagini recente » Cod sursa (job #2639196) | Cod sursa (job #3146149) | Cod sursa (job #2424311) | Cod sursa (job #1036910) | Cod sursa (job #2984455)
#include <bits/stdc++.h>
using namespace std;
ifstream in("zeap.in");
ofstream out("zeap.out");
typedef struct Treap* Arbore;
typedef pair<Arbore,Arbore>PAA;
const int INF = (1 << 30);
Arbore NIL;
Arbore root;
struct Treap
{
int key,prio,maxim,minim,mindif,sz;
Arbore left,right;
Treap(int val)
{
key = val;
prio = 1 + (rand() % INF);
maxim = val;
minim = val;
mindif = INF;
sz = 1;
left = NIL;
right = NIL;
}
};
void init()
{
NIL = new Treap(0);
root = NIL;
}
void recalc(Arbore x)
{
x->sz = x->left->sz + x->right->sz + 1;
x->minim = x->key;
x->maxim = x->key;
if (x->left != NIL)
x->minim = x->left->minim;
if (x->right != NIL)
x->maxim = x->right->maxim;
x->mindif = min(x->left->mindif,x->right->mindif);
if (x->left != NIL)
x->mindif = min(x->mindif,x->key - x->left->maxim);
if (x->right != NIL)
x->mindif = min(x->mindif,x->right->minim - x->key);
}
int cauta(Arbore x,int val)
{
if (x == NIL)
return 0;
if (x->key == val)
return 1;
if (x->key > val)
return cauta(x->left,val);
if (x->key < val)
return cauta(x->right,val);
}
Arbore join(Arbore a,Arbore b)
{
if (a == NIL)
return b;
if (b == NIL)
return a;
if (a->minim > b->minim)
swap(a,b);
if (a->prio > b->prio)
{
a->right = join(a->right,b);
recalc(a);
return a;
}
else
{
b->left = join(a,b->left);
recalc(b);
return b;
}
}
PAA split(Arbore x,int val)
{
if (x == NIL)
return {NIL,NIL};
if (val == x->key)
{
Arbore a1 = x->left;
x->left = NIL;
recalc(x);
return {a1,x};
}
else if (val < x->key)
{
PAA ans = split(x->left,val);
x->left = NIL;
recalc(x);
return {ans.first,join(ans.second,x)};
}
else if (val > x->key)
{
PAA ans = split(x->right,val);
x->right = NIL;
recalc(x);
return {join(x,ans.first),ans.second};
}
}
Arbore adauga(Arbore x,int val)
{
Arbore tr = new Treap(val);
PAA ans = split(x,val);
return join(join(ans.first,tr),ans.second);
}
Arbore sterge(Arbore x,int val)
{
if (x == NIL)
return NIL;
PAA fs = split(x,val);
PAA sec = split(fs.second,val + 1);
return join(fs.first,sec.second);
}
int main()
{
init();
string type;
while (in >> type)
{
if (type == "I")
{
int x;
in >> x;
if (cauta(root,x) == 0)
root = adauga(root,x);
}
else if (type == "S")
{
int x;
in >> x;
if (cauta(root,x) == 0)
out << "-1\n";
else
root = sterge(root,x);
}
else if (type == "C")
{
int x;
in >> x;
out << cauta(root,x) << '\n';
}
else if (type == "MAX")
{
if (root->sz <= 1)
out << "-1\n";
else
out << root->maxim - root->minim << '\n';
}
else if (type == "MIN")
{
if (root->sz <= 1)
out << "-1\n";
else
out << root->mindif << '\n';
}
}
return 0;
}