Cod sursa(job #2786885)

Utilizator cadmium_Voicu Mihai Valeriu cadmium_ Data 21 octombrie 2021 21:16:47
Problema Zeap Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.34 kb
#include <fstream>
#include <algorithm>
#define inf 2100000000
using namespace std;

ifstream cin("zeap.in");
ofstream cout("zeap.out");

namespace Treap {
  struct node {
    int val,pri;
    int maxx, minn;
    int dif;
    node *l, *r;
  } *nil = new node {0,0,-inf,inf,inf,0,0};
  using pn=node*;
  struct ppn {
    pn l,r;
  };
  pn mod(pn root, pn x, int mval) {
    if(mval==0)
      root->l=x;
    else
      root->r=x;
    root->maxx=max({root->l->maxx,root->r->maxx,root->val});
    root->minn=min({root->l->minn,root->r->minn,root->val});
    root->dif=min({root->l->dif,root->r->dif,root->val-root->l->maxx,root->r->minn-root->val});
    return root;
  }
  ppn split(pn root, int val) { // mai mic sau egal cu val
    ppn temp;
    //cout << root->maxx <<' '<< root->minn << ' '<< val << '\n';
    if(root->maxx<=val)
      return ppn{root,nil};
    if(root->minn>val) 
      return ppn{nil,root};
    if(root->val<=val) {
      temp=split(root->r,val);
      return {mod(root,temp.l,1),temp.r};
    }
    temp=split(root->l,val);
    return {temp.l,mod(root,temp.r,0)};
  }
  pn join(pn l, pn r) {
    //cout << l->val << ' '<< l->pri << '+'<< r-z>pri << '\n';
    if(l==nil)
      return r;
    if(r==nil)
      return l;
    if(l->pri>r->pri) 
      return mod(l,join(l->r,r),1);
    else
      return mod(r,join(l,r->l),0);
  }
  pn root=nil;
  void insert(int x) {
    ppn temp=split(root,x);
    root=join(join(temp.l,new node{x,rand(),x,x,inf,nil,nil}),temp.r);
  }
  void erase(int x) {
    ppn temp[2];
    temp[0]=split(root,x-1);
    temp[1]=split(temp[0].r,x);
    if(temp[1].l==nil)
      cout << "-1\n";
    else
      delete temp[1].l;
    root=join(temp[0].l,temp[1].r);
  }
  void find(int x) {
      ppn temp[2];
    temp[0]=split(root,x-1);
    temp[1]=split(temp[0].r,x);
    if(temp[1].l==nil)
      cout << "0\n";
    else
      cout << "1\n";
    root=join(temp[0].l,join(temp[1].l,temp[1].r));
  }
};

int main() {
  using namespace Treap;
  //srand(time(NULL));
  srand(0);
  string s;
  int x;
  while(cin >> s) {
    if(s=="MAX") {
      cout << (root->maxx<=root->minn? -1 : root->maxx-root->minn) <<'\n';
    }
    else if(s=="MIN") {
      cout << (root->maxx<=root->minn? -1 : root->dif) <<'\n';
    }
    else {
      cin >> x;
      if(s=="I")
        insert(x);
      else if(s=="S")
        erase(x);
      else 
        find(x);
    }
  }
  return 0;
}