Cod sursa(job #2298233)

Utilizator NToniBoSSNicolae Tonitza NToniBoSS Data 7 decembrie 2018 19:49:24
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.63 kb
#include <cstdio>
#include <utility>
#define val first
#define pos second
using namespace std;
int nr,n;
pair <int,int> chronological[200001],heap[200001];

int push(int x)
{
   int p=++n;
   heap[p]={x,nr};
   while(p>1 && heap[p].val<heap[p/2].val)
   {
      chronological[heap[p/2].pos].pos=p;
      chronological[heap[p].pos].pos=p/2;
      pair<int,int> aux=heap[p];
      heap[p]=heap[p/2];
      heap[p/2]=aux;
      p/=2;
   }
   if(!(p%2))
      if(heap[p].val>heap[p+1].val && p+1<=n)
      {
         chronological[heap[p+1].pos].pos=p;
         chronological[heap[p].pos].pos=p+1;
         pair<int,int> aux=heap[p];
         heap[p]=heap[p+1];
         heap[p+1]=aux;
         p++;
      }
      else ;
   else
      if(heap[p].val<heap[p-1].val)
      {
         chronological[heap[p-1].pos].pos=p;
         chronological[heap[p].pos].pos=p-1;
         pair<int,int> aux=heap[p];
         heap[p]=heap[p-1];
         heap[p-1]=aux;
         p--;
      }
   return p;
}

void pull(int p)
{
   chronological[heap[n].pos].pos=p;
   chronological[heap[p].pos].pos=n;
   pair<int,int> aux=heap[p];
   heap[p]=heap[n];
   heap[n]=aux;
   n--;
   while(p*2+1<=n && (heap[p].val>heap[p*2].val || heap[p].val>heap[p*2+1].val))
   {
      if(heap[p*2].val<heap[p*2+1].val)
      {
         chronological[heap[p*2].pos].pos=p;
         chronological[heap[p].pos].pos=p*2;
         pair<int,int> aux=heap[p];
         heap[p]=heap[p*2];
         heap[p*2]=aux;
         p=p*2;
      }
      else
      {
         chronological[heap[p*2+1].pos].pos=p*2;
         chronological[heap[p*2].pos].pos=p*2+1;
         pair<int,int> aux=heap[p*2];
         heap[p*2]=heap[p*2+1];
         heap[p*2+1]=aux;
         p=p*2+1;
      }
   }
   if(p*2<=n && heap[p].val>heap[p*2].val)
   {
       chronological[heap[p*2].pos].pos=p;
       chronological[heap[p].pos].pos=p*2;
       pair<int,int> aux=heap[p];
       heap[p]=heap[p*2];
       heap[p*2]=aux;
       p=p*2;
   }
}

int main()
{
   int q,x,p,c;
   int ct=0,ct2=0;
   freopen("heapuri.in","r",stdin);
   freopen("heapuri.out","w",stdout);
   scanf("%d",&q);
   while(q--)
   {
      scanf("%d",&c);
      if(c==1)
      {
         ct2++;
         if(ct2==2743)
            ct2=500;
         scanf("%d",&x);
         nr++;
         p=push(x);
         chronological[nr]={x,p};
         continue ;
      }
      if(c==2)
      {
         scanf("%d",&x);
         pull(chronological[x].pos);
         continue ;
      }
      ct++;
      if(ct==1764)
        ct=1765;
      printf("%d\n",heap[1].first);
   }

   return 0;
}