Cod sursa(job #1395873)

Utilizator vlad00Vlad Stoleru vlad00 Data 21 martie 2015 17:36:50
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>
const int NMAX=2000001;
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int h[NMAX], v[NMAX], invv[NMAX],nH;

int Father(int poz)
{
    return poz/2;
}

int LeftSon(int poz)
{
    return poz*2;
}

int RightSon(int poz)
{
    return LeftSon(poz)+1;
}

void UpHeap(int poz)
{
    while(h[poz]<h[Father(poz)] && poz>1)
    {
        swap(h[poz],h[Father(poz)]);
        swap(v[invv[poz]],v[invv[Father(poz)]]);
        swap(invv[poz],invv[Father(poz)]);
        poz=Father(poz);
    }
}

void DownHeap(int poz)
{
    bool ok=true;
    while(ok)
    {
        ok=false;
        if(LeftSon(poz)>nH)
            break;
        int fs=h[LeftSon(poz)],w=0;
        if(RightSon(poz)<=nH&&h[RightSon(poz)]<fs)
            w=1;
        if(w==0)
        {
            if(fs<h[poz])
            {
                swap(h[LeftSon(poz)],h[poz]);
                swap(v[invv[poz]],v[invv[Father(poz)]]);
                swap(invv[poz],invv[Father(poz)]);
                poz=LeftSon(poz);
                ok=true;
            }
        }
        else
        {
            if(h[RightSon(poz)]<h[poz])
            {
                swap(h[RightSon(poz)],h[poz]);
                swap(v[invv[poz]],v[invv[Father(poz)]]);
                swap(invv[poz],invv[Father(poz)]);
                poz=RightSon(poz);
                ok=true;
            }
        }
    }
}

int minim()
{
    return h[1];
}

int main()
{
    int q,flag=0;
    f>>q;
    while(q--)
    {
        int cod;
        f>>cod;
        if(cod==1)
        {
            int x;
            f>>x;
            flag++;
            nH++;
            h[nH]=x;
            v[flag]=nH;
            invv[nH]=flag;
            UpHeap(nH);
        }
        if(cod==2)
        {
            int x;
            f>>x;
            int a=v[x];
            invv[a]=invv[nH];
            v[invv[nH]]=a;
            swap(h[nH],h[v[x]]);
            --nH;
            UpHeap(a);
            DownHeap(a);
        }
        if(cod==3)
            g<<minim()<<'\n';
    }
    f.close();
    g.close();
    return 0;
}