Cod sursa(job #545390)

Utilizator nautilusCohal Alexandru nautilus Data 3 martie 2011 11:28:47
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<fstream>
#define dmax 200010
using namespace std;

typedef struct nod
{
 long long e;
 int in;
} nod;

nod h[dmax];
int lg,elem;
int ord[dmax];
/*ord[i] = pe ce pozitie in heap este al i-lea element introdus*/

int tata(int x)
{
 return x / 2;
}

int fiu_stg(int x)
{
 return 2 * x;
}

int fiu_dr(int x)
{
 return 2 * x + 1;
}


void up(int poz)
{
 nod elem = h[poz];
 
 while (poz > 1 && elem.e < h[tata(poz)].e)
	 {
	  ord[h[tata(poz)].in] = poz;
      h[poz] = h[tata(poz)];
	  
	  poz = tata(poz);
	 }
 
 h[poz] = elem;
 ord[h[poz].in] = poz;
}


void down(int poz)
{
 int fiu = 0;
 
 do
	 {
	  fiu = 0;
	  
	  if (fiu_stg(poz) <= lg)
		  {
		   fiu = fiu_stg(poz);
	     
		   if (fiu_dr(poz) <= lg && h[fiu_stg(poz)].e > h[fiu_dr(poz)].e)
			  fiu = fiu_dr(poz);
		  
		   if (h[poz].e <= h[fiu].e)
			  fiu = 0;
		  }
	  
	  if (fiu != 0)
		  {
		   swap(ord[h[poz].in], ord[h[fiu].in]);
		   swap(h[poz], h[fiu]);
		   poz = fiu;
		  }
	 }
 while (fiu != 0);
}


void add(int x)
{
 lg++; elem++;
 h[lg].e = x; h[lg].in = elem;
 ord[elem] = lg;
 
 up(lg);
}


void erase(int x)
{
 int eh = ord[x];
 
 ord[h[lg].in] = eh;
 h[eh] = h[lg]; lg--;
 
 if (eh > 1 && h[eh].e < h[tata(eh)].e)
	 up(eh); else
	 down(eh);
}


void citire()
{
 int n,i,op,x;
    
 ifstream fin("heapuri.in");
 ofstream fout("heapuri.out");
 
 fin>>n;
 for (i=1; i<=n; i++)
     {
      fin>>op;
      if (op == 1)
          {
           fin>>x;
           add(x);
          } else
          if (op == 3)
              fout<<h[1].e<<'\n'; else
              {
               fin>>x;
               erase(x);
              }
     }
    
 fin.close();
 fout.close();
}


int main()
{
	
 citire();
	
 return 0;
}