Cod sursa(job #1193450)

Utilizator Cristian1997Vintur Cristian Cristian1997 Data 31 mai 2014 19:48:14
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
using namespace std;
#include <fstream>
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int Nmax = 200000;

int heap[Nmax+5], lg=0; // heap care contine indicii elementelor in vectorul v
int v[Nmax+5], nr=0;    // numerele citite in ordine
int poz[Nmax+5];        // pozitia in heap a elementului de pe pozitia i in vectorul v

void adauga(int) ;
void sterge(int) ;
void swap1(int, int) ;

int main()
{
    int i, n, a, tip;
    fin>>n;
    for(i=0; i<n; ++i)
    {
        fin>>tip;
        if(tip==3) fout<<v[heap[1]]<<'\n';
        else
        {
            fin>>a;
            if(tip==1) adauga(a);
            else sterge(poz[a]);
        }
    }
    return 0;
}


void adauga(int val)
{   //adauga elementul val
    nr++; lg++;
    v[nr] = val; heap[lg] = nr; poz[nr] = lg;
    int tata = lg/2, fiu = lg;
    while(tata>=1 && v[heap[tata]]>val)
    {
        swap1(fiu, tata);
        fiu = tata;
        tata>>=1;
    }
}


void sterge(int p)
{   //sterge elementul de pe pozitia p
    if(p<0 || p>nr) return;
    poz[heap[p]] = 0;
    heap[p] = heap[lg];
    poz[heap[p]] = p;
    heap[lg] = 0; --lg;
    int fiu;
    while(2*p<=lg)
    {   //stim sigur ca are fiu stang
        if(2*p==lg)
        {//nu are fiu drept
            if(v[heap[2*p]] < v[heap[p]])
                swap1(p, 2*p);
            return;
        }
        else
        {
            fiu = 2*p;
            if(v[heap[fiu]]>v[heap[fiu+1]]) ++fiu;
                //fiu - cel mai mic dintre fii
            if(v[heap[p]]>v[heap[fiu]])
            {
                swap1(p, fiu);
                p = fiu;
            }
            else return;
        }
    }
}


void swap1(int a, int b)
{   //intershimba elementele de pe pozitiile a si b din heap
    int aux = heap[a];
    heap[a] = heap[b];
    heap[b] = aux;
    poz[heap[a]] = a;
    poz[heap[b]] = b;
}