Cod sursa(job #1193423)

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

const int Nmax = 200000;

int heap[Nmax+5];
int v[Nmax+5], nr=0;
int poz[Nmax+5];

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<<heap[1]<<'\n';
        else
        {
            fin>>a;
            if(tip==1) adauga(a);
            else sterge(poz[v[a]]);
        }
    }
    return 0;
}


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


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