Cod sursa(job #922799)

Utilizator thebest001Neagu Rares Florian thebest001 Data 22 martie 2013 17:34:33
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include<fstream>
#define NM 200001
using namespace std;

ifstream in("heapuri.in");
ofstream out("heapuri.out");

int t,h[NM],a[NM],poz[NM],po,n,m,x,u;
void swap(int x,int y)
{
    int aux;
    aux=poz[a[x]];
    poz[a[x]]=poz[a[y]];
    poz[a[y]]=aux;
    aux=h[x];
    h[x]=h[y];
    h[y]=aux;
    aux=a[x];
    a[x]=a[y];
    a[y]=aux;
}
int min(int a,int b)
{
    if(h[a]>h[b])
    return b;
    return a;
}
void urca(int k){
    while(h[k]<h[k/2]&&k>=2){
        swap(k,k/2);
        k/=2;
    }
}
void coboara(int k)
{
    while(k*2<=n&&(h[k]>h[k*2]||h[k]>h[k*2+1]))
    {
        int c=min(k*2,k*2+1);
        if(k*2+1>n)
        c=k*2;
        swap(c,k);
        k=c;
    }
}
int main(){
    int tmp;


    in>>m;

    for(int i=1;i<=m;++i){
        in>>tmp;
        if(tmp==1)
        {
            in>>x;
            ++u;
            n++;
            a[n]=u;
            poz[u]=n;
            h[n]=x;
            urca(n);
        }
        if(tmp==2)
        {
            in>>x;
            po=poz[x];
            swap(poz[x],n);
            h[n]=a[n]=poz[x]=0;
            n--;
            if(po<=n){
                urca(po);
                coboara(po);
            }
        }
        if (tmp==3)
            out<<h[1]<<"\n";
    }
    return 0;
}