Cod sursa(job #742145)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 28 aprilie 2012 18:36:36
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#include<assert.h>

#include<vector>
#include<algorithm>

using namespace std;

struct keys{
  int val, pos;

  keys(){};

  bool operator > (keys two){
    return val < two.val;
  }

};

const int kmin = 1000000005;

class max_heap{
public:
  max_heap *left, *right;
  keys key;

  max_heap(){};

  max_heap(int x){left = right = NULL;key.val = x;key.pos = 0;};

  void push(keys x){
    if(x > key)
      swap(x, key);

    int aux = rand() % 2;

    if(aux == 0){
      if(left == NULL){
        left = new max_heap;
        (*left).left = (*left).right = NULL;
        (*left).key = x;
      }
      else
        (*left).push(x);

    }
    else{
      if(right == NULL){
        right = new max_heap;
        (*right).left = (*right).right = NULL;
        (*right).key = x;
      }
      else
        (*right).push(x);

    }

  }

  void pop(){
    if(left != NULL && right != NULL){
      if((*left).key > (*right).key)
        swap((*left), (*right));

      key = (*right).key;

      (*right).pop();
    }
    else{
      if(right == NULL && left == NULL){
        key.val = kmin;
        return ;
      }

      if(right == NULL)
        swap(right, left);

      max_heap *aux = right;

      key = (*right).key;
      left = (*right).left;
      right = (*right).right;

      delete aux;
    }

  }

  keys top(){
    return key;
  }

};

const int knmax = 200005;
int operations, u, bad[knmax];

void read(){
  assert(freopen("heapuri.in", "r", stdin));
  assert(freopen("heapuri.out", "w", stdout));

  scanf("%d", &operations);
}

void write(int x){
  printf("%d\n", x);
}

void solve(){
  int optype;
  max_heap h(kmin);

  for(int i = 1; i <= operations; ++i){
    scanf("%d", &optype);

    if(optype == 1){
      keys aux;
      scanf("%d", &aux.val);
      ++u;
      aux.pos = u;
      h.push(aux);
    }
    if(optype == 2){
      int aux;
      scanf("%d", &aux);
      bad[aux] = 1;
    }
    if(optype == 3){
      while(bad[(h.top()).pos])
        h.pop();

      write((h.top()).val);
    }

  }

}

int main(){
  srand(time(NULL));

  read();
  solve();
  return 0;
}