Cod sursa(job #1812268)

Utilizator RadduFMI Dinu Radu Raddu Data 21 noiembrie 2016 22:25:31
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#define inf (1<<30)
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int n,kth[200005],num;

struct heap
{
    int x,ord;
} h[200005];

void swp(heap &h1,heap &h2)
{ swap(kth[h1.ord],kth[h2.ord]);
  swap(h1,h2);
}

void Percolate(int pos)
{ int ans=0;

  while(pos/2 && h[pos].x<h[pos/2].x)
  { swp(h[pos],h[pos/2]);
    pos/=2;
  }

}

void Sift(int pos)
{ int val,ind=0,ok=1;

  while(ok)
  {
    ok=0; val=inf;

    if (pos*2<=n)
        {val=h[pos*2].x; ind=pos*2;}

    if (pos*2+1<=n && h[pos*2+1].x<h[pos*2].x)
        {val=h[pos*2+1].x; ind=pos*2+1;}

    if (val<h[pos].x)
         {
          swp(h[pos],h[ind]);
          pos=ind;
          ok=1;
         }

  }

}

int Ins(int x)
{
  n++; num++;
   kth[num]=n;
  h[n].x=x; h[n].ord=num;
  Percolate(n);
}

void Del(int x)
{ int ans=0;

  swp(h[x],h[n]);

  n--;

  if (n && x!=n+1)
  {
    if (x/2 && h[x].x<h[x/2].x) Percolate(x);
     else Sift(x);
  }
}

int main()
{ int x,t,caz,i,j;
  f>>t;

  for(i=1;i<=t;i++)
  { f>>caz;

      if (caz==1)
      { f>>x; Ins(x); }

      if (caz==2)
      { f>>x;
        Del(kth[x]);
      }

      if (caz==3)
        g<<h[1].x<<"\n";
  }
    return 0;
}