Cod sursa(job #1298892)

Utilizator witselWitsel Andrei witsel Data 23 decembrie 2014 12:10:06
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int NMAX=200000;
int H[NMAX],v[NMAX],n,N,i,m,op,j,x,aux;
void inserare(int);
void percolate(int);
void stergere(int);
void shift(int );
int main()
{
    fin>>N;
    while(N--)
    {
        fin>>op;
        switch(op)
        {
            case 1:fin>>x;
                    n++;
                    v[++j]=x;
                    inserare(v[j]);
                    break;
            case 2:fin>>x; stergere(v[x]);
            break;
            case 3:fout<<H[1]<<"\n";
        }
    }

}

void inserare(int x)
{
    H[n]=x;
    percolate(n);
}
void percolate(int k)
{
    while(k>1 && H[k]<H[k/2])
    {
        aux=H[k];
        H[k]=H[k/2];
        H[k/2]=aux;
        k=k/2;
    }
}
 void stergere(int val)
 {
     for(i=1;i<=n && H[i]!=val;i++);
     aux=H[i];
     H[i]=H[n];
     H[n]=aux;
     n--;
     if(H[i]<H[i/2])
        percolate(i);
     else shift(i);
 }
 void shift(int k)
 {
     int ok=1;
     while(k<=n/2 && ok==1)
     {
         ok=0;
         if(k*2+1<=n && H[k*2+1]<=H[k*2] && H[k]>H[k*2+1])
         {
             aux=H[k*2+1];
             H[k*2+1]=H[k];
             H[k]=aux;
             k=k*2+1;
             ok=1;
         }
         else if(H[k]>H[2*k])
         {
             aux=H[k];
             H[k]=H[2*k];
             H[2*k]=aux;
             k=2*k;
             ok=1;
         }
     }
 }