Cod sursa(job #545246)

Utilizator nautilusCohal Alexandru nautilus Data 2 martie 2011 22:57:49
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include<fstream>
#define dmax 200010
using namespace std;

typedef struct heap
{
 int e,in;
} heap;

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

void stanga(int poz);
void dreapta(int poz);

void urca(int poz)
{
 while (h[poz].e < h[poz / 2].e && poz > 1)
	 {
      swap(ord[h[poz].in], ord[h[poz/2].in]);
	  swap(h[poz], h[poz / 2]);
	  
	  stanga(poz);
	  
      poz = poz / 2;
     }
}


void coboara(int poz)
{
 while (h[poz].e > h[poz * 2].e && poz <= lg / 2)
     {
      swap(h[poz], h[poz * 2]);
      swap(ord[h[poz].in], ord[h[poz * 2].in]);
      
	  dreapta(poz);
	  dreapta(poz * 2);
      
      poz = poz * 2;
     }
}


void dreapta(int poz)
{
 int aux=0,pmax;
 while ((1<<aux) <= poz)
	 aux++;
 pmax = (1<<aux) - 1;
 
 while (h[poz].e > h[poz + 1].e && poz + 1 <= min(pmax, lg))
     {
      swap(h[poz], h[poz + 1]);
      swap(ord[h[poz].in], ord[h[poz + 1].in]);
      
      poz++;
     }
}


void stanga(int poz)
{
 int aux=0,pmin;
 while ((1<<aux) <= poz)
	 aux++;
 aux--;
 pmin = 1<<aux;
 
 while (h[poz].e < h[poz - 1].e && poz - 1 >= pmin)
     {
      swap(h[poz], h[poz - 1]);
      swap(ord[h[poz].in], ord[h[poz - 1].in]);
      
      poz--;
     }
}


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


void erase(int x)
{
 int eh = ord[x]; 
 /*eh = poz elementului din heap care trebuie eliminat*/
 
 h[eh] = h[lg]; ord[h[lg].in] = eh; 
 lg--;
 
 coboara(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;
}