Cod sursa(job #2035647)

Utilizator LizaSzabo Liza Liza Data 9 octombrie 2017 18:41:15
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int NMax = 200005;
int V[NMax],Heap[NMax],Pos[NMax];
int M,N,NHeap;

void UpHeap(int X)
{
  int Father = X/2;
  if(Father && V[Heap[Father]] > V[Heap[X]])
  {
    swap(Heap[Father],Heap[X]);
    swap(Pos[Heap[Father]],Pos[Heap[X]]);
    UpHeap(Father);
  }
}

void DownHeap(int X)
{
  int Son1 = 2*X,Son2 = 2*X+1,Son;
  if(Son1 > NHeap)
    return;
  if(Son1 == NHeap)
  {
    if(V[Heap[Son1]] < V[Heap[X]])
      swap(Heap[Son1],Heap[X]);
      swap(Pos[Heap[Son1]],Pos[Heap[X]]);
    return;
  }
  if(V[Heap[Son1]] < V[Heap[Son2]])
    Son = Son1;
  else
    Son = Son2;
  if(V[Heap[Son]] < V[Heap[X]])
  {
    swap(Heap[Son],Heap[X]);
    swap(Pos[Heap[Son]],Pos[Heap[X]]);
    DownHeap(Son);
  }
}

int main()
{
    fin >> M;
    while(M--)
    {
      int op,x;
      fin >> op;
      if(op < 3)
        fin >> x;
      if(op == 1)
      {
        V[++N] = x;
        Heap[++NHeap] = N;
        Pos[N] = NHeap;
        UpHeap(NHeap);
      }
      if(op == 2)
        {
          Heap[Pos[x]] = Heap[NHeap];
          Pos[Heap[NHeap]] = Pos[x];
          NHeap--;
          DownHeap(Pos[x]);
        }
      if(op == 3)
        {
          fout << V[Heap[1]] << "\n";
        }
    }
    return 0;
}