Cod sursa(job #950168)

Utilizator mihai.agapeMihai Agape mihai.agape Data 16 mai 2013 00:15:33
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <algorithm>
#include <fstream>
#define NMAX 200001
using namespace std;

class heap
{
  private:
    int sz;
    int num_of_inserts;
    vector<pair<int,int>> el;
    vector<int> el_pos;

    void el_swap(int pos_a, int pos_b)
    {
      swap(el_pos[el[pos_a].second], el_pos[el[pos_b].second]);
      swap(el[pos_a], el[pos_b]);
    }

  public:
    heap()
    {
      sz = 0;
      num_of_inserts = 0;
      el = vector<pair<int,int>>(NMAX);
      el_pos = vector<int>(NMAX);
    }

    void bubble_up(int s)
    {
      auto f=s>>1;
      while(s>1 && el[f].first>el[s].first)
	el_swap(s, f), s>>=1;
    }

    void bubble_down(int f)
    {
      int l=f<<1, r=l+1, nf;

      for(;;)
      {
	nf=f;
	if(r>sz || (l<sz && el[l].first<el[r].first))
	  nf=l;
	else if(r<=sz && el[r].first<el[l].first)
	  nf=r;
	if(nf!=f && el[nf].first<el[f].first)
	  el_swap(f, nf), f=nf;
	else
	  return;
      }
    }

    void push(int val)
    {
      el[++sz]=pair<int,int>(val, ++num_of_inserts);
      el_pos[num_of_inserts]=sz;
      bubble_up(sz);
    }

    int peek()
    {
      return el[1].first;
    }

    void pop(int t)
    {
      int f=el_pos[t];
      el_swap(f, sz--);
      bubble_up(f);
      bubble_down(f);
    }
};

int main()
{
  int n, op, arg;
  heap h;
  ifstream fin("heapuri.in");
  ofstream fout("heapuri.out");

  fin>>n;
  while(n--)
  {
    fin>>op;
    switch(op)
    {
      case 1:
	fin>>arg;
	h.push(arg);
	break;
      case 2:
	fin>>arg;
	h.pop(arg);
	break;
      case 3:
	fout<<h.peek()<<"\n";
	break;
    }
  }

  return 0;
}