Cod sursa(job #1052271)

Utilizator AnonymouslegionAnonymous Anonymouslegion Data 10 decembrie 2013 23:40:45
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.38 kb
#include <fstream>
#include <vector>

using namespace std;

template<class T>
class node{
public:

  node<T> *lt, *rt, *dad;
  T key;

  node(){};

  node(T x, node<T> *dad1){
    key = x;
    dad = dad1;
  }
};

template<class T>
class randomset{
public:

  randomset(){
    NIL = new node<T>;
    BN = new node<T>;
    root = new node<T>;
    root->dad = BN;
  }

  void add(T x){
    node<T> *added = new node<T>(x, NIL);
    added->lt = NIL;
    added->rt = NIL;
    insert(added);
  }

  void del(T x){
    node<T> *deled = find(x);
    erase(deled);
  }

  T min(){
    return (*min(root)).key;
  }

private:
  node<T> *NIL, *root, *BN, *p, *q, *r;

  void insert(node<T> *x){
    if(root->dad == BN){
      root = x;
      x->dad = NIL;
      return;
    }
    p = root;
    while(1){
      if(p->key > x->key){
        if(p->lt == NIL){
          p->lt = x;
          x->dad = p;
          return;
        }
        else
          p = p->lt;
      }
      else{
        if(p->rt == NIL){
          p->rt = x;
          x->dad = p;
          return;
        }
        else
          p = p->rt;
      }
    }
  }

  node<T> *min(node<T> *start){
    while(start->lt != NIL)
      start = start->lt;
    return start;
  }

  node<T> *max(node<T> *start){
    while(start->rt != NIL)
      start = start->rt;
    return start;
  }

  node<T> *find(T val){
    p = root;
    while(p->key != val && p != NIL)
      if(p->key > val)
        p = p->lt;
      else
        p = p ->rt;
    return p;
  }

  void erase(node<T> *bad){
    p = bad;

    if(p->lt == NIL && p->rt == NIL){
      forget();
      delete p;
      return;
    }

    if(p->rt){
      q = min(p->rt);
      T aux = q->key;
      q->key = p->key;
      p->key = aux;
      erase(q);
      return;
    }

    q = max(p->lt);
    T aux = q->key;
    q->key = p->key;
    p->key = aux;
    erase(q);
    return;
  }

  void forget(){
    if(p->dad == NIL)
      return;
    if(p->dad->key > p->key)
      p->dad->lt = NIL;
    else
      p->dad->rt = NIL;
  }
};

randomset<int> h;

int main(){
  ifstream in("heapuri.in");
  ofstream out("heapuri.out");

  int n;
  vector<int> op;
  in >> n;

  int x;
  for(int i = 1; i <= n; ++i){
    int tip;
    in >> tip;

    if(tip == 1){
      in >> x;
      op.push_back(x);
      h.add(x);
    }
    else if(tip == 2){
      in >> x;
      h.del(op[x - 1]);
    }
    else
      out << h.min() << "\n";
  }

  return 0;
}