Pagini recente » testttttttt | Cod sursa (job #2011866) | Monitorul de evaluare | Cod sursa (job #1570840) | Cod sursa (job #1694145)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
using namespace std;
struct nod{
int val, max_sub, min_sub, min_dif, priority, sz;
nod *st, *dr; };
void reset_nod(nod *n){
n->max_sub = n->min_sub = n->val;
n->min_dif = 1000 * 1000 * 1000 + 10;
n->sz = 1;
if(n->st){
n->max_sub = max(n->max_sub, n->st->max_sub);
n->min_sub = min(n->min_sub, n->st->min_sub);
n->min_dif = min({n->min_dif, n->st->min_dif, n->val - n->st->max_sub});
n->sz += n->st->sz; }
if(n->dr){
n->max_sub = max(n->max_sub, n->dr->max_sub);
n->min_sub = min(n->min_sub, n->dr->min_sub);
n->min_dif = min({n->min_dif, n->dr->min_dif, n->dr->min_sub - n->val});
n->sz += n->dr->sz; } }
nod *caut(nod *n, const int v){
if(!n || n->val == v){
return n; }
return caut((n->val < v) ? n->dr : n->st, v); }
nod *rotate_left(nod *n){
nod *aux = n->dr;
n->dr = aux->st;
aux->st = n;
reset_nod(n);
reset_nod(aux);
return aux; }
nod *rotate_right(nod *n){
nod *aux = n->st;
n->st = aux->dr;
aux->dr = n;
reset_nod(n);
reset_nod(aux);
return aux; }
nod *sterge(nod *n, const int x, bool& found){
if(!n){
found = false;
return nullptr; }
else if(n->val == x){
if(!n->st){
nod *tmp = n->dr;
delete n;
return tmp; }
if(!n->dr){
nod *tmp = n->st;
delete n;
return tmp; }
if(n->st->priority > n->dr->priority){
n = rotate_right(n);
n->dr = sterge(n->dr, x, found);
reset_nod(n);
return n; }
else{
n = rotate_left(n);
n->st = sterge(n->st, x, found);
reset_nod(n);
return n; } }
else if(n->val > x){
n->st = sterge(n->st, x, found); }
else{
n->dr = sterge(n->dr, x, found); }
reset_nod(n);
return n; }
nod *insereaza(nod *n, const int x){
if(!n){
nod *tmp = new nod;
*tmp = (nod){ x, x, x, 1000 * 1000 * 1000 + 10, rand(), 1, nullptr, nullptr};
return tmp; }
if(n->val > x){
n->st = insereaza(n->st, x);
if(n->priority < n->st->priority){
return rotate_right(n); }
reset_nod(n);
return n; }
if(n->val == x){
return n; }
if(n->val < x){
n->dr = insereaza(n->dr, x);
if(n->priority < n->dr->priority){
return rotate_left(n); }
reset_nod(n);
return n; } }
int max_dif(nod *n){
if(!n || n->sz == 1){
return -1; }
return n->max_sub - n->min_sub; }
int min_dif(nod *n){
if(!n || n->sz == 1){
return -1; }
return n->min_dif; }
int main(){
ifstream f("zeap.in");
ofstream g("zeap.out");
string str;
int x;
nod *rad = nullptr;
while(f >> str){
if(str == "I"){
f >> x;
rad = insereaza(rad, x); }
else if(str == "S"){
bool found = true;
f >> x;
rad = sterge(rad, x, found);
if(!found){
g << -1 << '\n'; } }
else if(str == "C"){
f >> x;
g << (caut(rad, x) != nullptr) << '\n'; }
else if(str == "MAX"){
g << max_dif(rad) << '\n'; }
else{
g << min_dif(rad) << '\n'; } }
return 0; }