Cod sursa(job #1806405)

Utilizator DjokValeriu Motroi Djok Data 15 noiembrie 2016 11:59:59
Problema Zeap Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.46 kb
#include <bits/stdc++.h>
using namespace std;

typedef struct treap {
  int key, prior, dmin;
  treap *left, *right;
  treap(int _key = 0) { key = _key; dmin = -1; prior = rand(); left = right = 0; }
}*Treap;

const int INF = 1e9 + 69 * 69;

int i, n, x, rs;
string op;
Treap root;

void tupd(Treap &root) {
  if(!root) return;
  root->dmin = INF;
  if(root->left) {
    root->dmin = min(root->dmin, abs(root->key - root->left->key));
    root->dmin = min(root->dmin, root->left->dmin);
  }
  if(root->right) {
    root->dmin = min(root->dmin, abs(root->key - root->right->key));
    root->dmin = min(root->dmin, root->right->dmin);
  }
}

void tsplit(Treap root, int key, Treap &l, Treap &r) {
  if(!root) l = r = 0;
  else if(key < root->key) tsplit(root->left, key, l, root->left), r = root;
       else tsplit(root->right, key, root->right, r), l = root;
  tupd(root);
}

void tmerge(Treap &root, Treap l, Treap r) {
  if(!l || !r) root = (l ? l : r);
  else if(l->prior > r->prior) tmerge(l->right, l->right, r), root = l;
       else tmerge(r->left, l, r->left), root = r;
  tupd(root);
}

void tinsert(Treap &root, Treap now) {
  if(!root) root = now;
  else if(root->prior < now->prior) tsplit(root, now->key, now->left, now->right), root = now;
       else if(root->key < now->key) tinsert(root->right, now);
            else if(root->key > now->key) tinsert(root->left, now);
  tupd(root);
}

void terase(Treap &root, int key) {
  if(!root) rs = -1;
  else if(root->key == key) tmerge(root, root->left, root->right), rs = 0;
       else if(root->key < key) terase(root->right, key);
            else terase(root->left, key);
  tupd(root);
}

bool tfind(Treap &root, int key) {
  if(!root) return 0;
  if(root->key == key) return 1;
  if(root->key < key) return tfind(root->right, key);
  return tfind(root->left, key);
}

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

  ios_base::sync_with_stdio(0);

  while(cin >> op) {
    if(op == "I") cin >> x, tinsert(root, new treap(x));

    if(op == "S") {
      cin >> x; terase(root, x);
      if(rs == -1) cout << "-1\n";
    }

    if(op == "C") cin >> x, cout << tfind(root, x) << '\n';

    if(op == "MAX") {
      for(Treap it = root; it; it = it->left) rs = it->key;
      for(Treap it = root; it; it = it->right) x = it->key;
      cout << x - rs << '\n';
    }

    if(op == "MIN") cout << (root ? root->dmin : -1) << '\n';
  }

  return 0;
}