Cod sursa(job #1340636)

Utilizator Pintilie_AndreiFII-Pintilie Andrei Pintilie_Andrei Data 11 februarie 2015 22:24:06
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#define N 200004
using namespace std;
int h[N],top;
int v[N],nr;
int poz[N];
int Tata(int nod)
{
    return nod/2;
}
int Lson(int nod)
{
    return nod*2;
}
int Rson(int nod)
{
    return nod*2+1;
}

void Percolate(int k)
{
    int key=h[k];
    while(k>1 && h[Tata(k)]>key)
    {
        poz[h[Tata(k)]]=k;
        h[k]=h[Tata(k)];
        k=Tata(k);

    }
    poz[key]=k;
    h[k]=key;
}

void Sift(int k)
{
    int son=Lson(k);
    while(son)
    {
        son=0;
        if(Lson(k)<=top)
        {
            son=Lson(k);
            if(Rson(k)<=top && h[Rson(k)]<h[son])
                son=Rson(k);
            if(h[son]>=h[k]) son=0;
        }
        if (son)
        {
            poz[h[son]]=k;
            poz[h[k]]=son;
            swap(h[son],h[k]);

            k=son;
        }
    }
}

void Op1(int x)
{
    top++;
    h[top]=x;
    Percolate(top);
}
void Op2(int x)
{
    h[x]=h[top];
    top--;

    if(x>1 && h[x]<h[Tata(x)])
        Percolate(x);
    else Sift(x);
}
ofstream fout("heapuri.out");
void Op3()
{
    fout<<h[1]<<"\n";
}
void Afisare()
{
    for(int i=1; i<=top; i++)
        cout<<h[i]<<" "<<poz[7]<<"\n";
    cout<<"\n";
}
int CautaB(int x)
{
    for(int i=1; i<=top; i++)
        if(h[i]==x) return i;
}

//int Cauta1(int x,int poz)
//{
//    //cout<<h[poz<<" "<<x<<"\n";
//    if(h[poz]==x) return poz;
//    if(Rson(poz)<=top)
//       if ( h[Rson(poz)]<=x ) return Cauta1(x,Rson(poz));
//    if(Lson(poz)<=top)
//        if ( h[Lson(poz)]<=x) return Cauta1(x,Lson(poz));
//}

int main()
{
    int k,com,x,pozi,i;
    ifstream fin("heapuri.in");
    fin>>k;
    for(i=1; i<=k; i++)
    {
       fin>>com;
       if(com==1)
       {
           fin>>x;
           Op1(x);
           v[++nr]=x;
       }
       if(com==2)
       {
           fin>>x;
           pozi=CautaB(v[x]);
           //cout<<pozi<<" "<<poz[v[x]]<<"\n";
           //Afisare();
           Op2(poz[v[x]]);
       }
       if(com==3) Op3();
    }
    return 0;
}