Cod sursa(job #518209)

Utilizator dicu_dariaDaria Dicu dicu_daria Data 30 decembrie 2010 18:57:57
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
//heapuri 2.0
#include <fstream>

using namespace std;
int m,n,heap[200005],a[200005],poz[200005];
int left(int i)
{
    return (2*i);
}
int right(int i)
{
    return (2*i+1);
}
int father(int i)
{
    return (i/2);
}
void urca(int i)
{
    int key=heap[i];
    while(i>1 and a[heap[father(i)]]>a[key])
    {
        heap[i]=heap[father(i)];
        poz[father(i)]=i;
        i=father(i);
    }
    heap[i]=key; poz[key]=i;
}
void coboara(int i)
{
    int minim;
    minim=i;
    if(left(i)<=n and a[heap[left(i)]]<a[heap[i]]) minim=left(i);
    if(right(i)<=n and a[heap[right(i)]]<a[heap[minim]])minim=right(i);
    if(minim!=i){swap(heap[i],heap[minim]);
                 swap(poz[heap[i]],poz[heap[minim]]);
                 coboara(minim);}

}
void sterge(int i)
{
    heap[i]=heap[n];
    poz[heap[n]]=i;
    n--;
    if(i>1 and a[heap[father(i)]]>a[heap[i]])
    urca(i);
    else
    coboara(i);
}
int main()
{
    int t,x,tip;
    ifstream fi("heapuri.in");
    ofstream fo("heapuri.out");
    fi>>t;
    while(t--)
    {
        fi>>tip;
        if(tip<3) fi>>x;
        if(tip==1) {
                    a[++m]=x;
                    heap[++n]=m;
                    poz[m]=n;
                    urca(n);
                   }
        if(tip==2)
        sterge(poz[x]);
        if(tip==3) fo<<a[heap[1]]<<"\n";
    }
    return 0;
}