Cod sursa(job #1843691)

Utilizator raduzxstefanescu radu raduzx Data 9 ianuarie 2017 03:34:35
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <fstream>

using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int v[200004],n,poz[200004],heap[200004],cate=0,nrheap;
void swa(int x,int y)
{
    int t;
    t=heap[x];
    heap[x]=heap[y];
    heap[y]=t;
}
void upheap(int k)
{
    int t;
    while(k>1 and v[heap[k]]<v[heap[k/2]])
    {
        swa(k,k/2);
        poz[heap[k]]=k;
        poz[heap[k/2]]=k/2;
        k/=2;
    }
}
/*void downheap(int k)
{
    int t;
    do
    {
        t=0;
        if(k*2<=nrheap)
        {
            t=k*2;
            if(t+1<=k and v[heap[t+1]]<v[heap[t]])
            {
                t+=1;
            }
            if(v[heap[k]]>=v[heap[t]])
            {
                swa(k,t);
                poz[heap[k]]=k;
                poz[heap[t]]=t;
            }
            k=t;
        }
    }while(t);
}*/
void downheap(int x)
{
    int aux, y = 0;

    while (x != y)
    {
        y = x;

        if (y*2<=nrheap && v[heap[x]]>v[heap[y*2]]) x = y*2;
        if (y*2+1<=nrheap && v[heap[x]]>v[heap[y*2+1]]) x = y*2+1;

        aux = heap[x];
        heap[x] = heap[y];
        heap[y] = aux;

        poz[heap[x]] = x;
        poz[heap[y]] = y;
    }
}
void bun(int k)
{
    if(2*k<=nrheap)
    {
        if(v[heap[k]]>v[heap[2*k]])
            g<<"rau";
        else
            if(2*k+1<=nrheap)
                if(v[heap[k]]>v[heap[2*k+1]])
                    g<<"rau";
                else
                {
                    bun(2*k);
                    bun(2*k+1);
                }
            else
                bun(2*k);
    }
}
int main()
{
    int i,nr,x;
    f>>n;
    for(i=1;i<=n;i++)
    {
        f>>nr;
        if(nr==1)
        {
            f>>x;
            cate+=1;
            nrheap+=1;
            v[cate]=x;
            poz[cate]=nrheap;
            heap[nrheap]=cate;
            upheap(nrheap);
        }
        else
            if(nr==3)
            {
                g<<v[heap[1]]<<'\n';
            }
            else
            {
                f>>x;
                v[x]=-1;
                upheap(poz[x]);


                poz[heap[1]]=0;
                heap[1]=heap[nrheap];
                nrheap-=1;
                poz[heap[1]]=1;
                if(nrheap>1)
                    downheap(1);
            }
    }
    return 0;
}