Cod sursa(job #1041314)

Utilizator a96tudorAvram Tudor a96tudor Data 25 noiembrie 2013 18:56:24
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include<cstdio>
#include<cstring>
#include<vector>

#define pb push_back
#define N_MAX 200010
using namespace std;



int H[N_MAX],poz[N_MAX],V[N_MAX];

int i,N,k,x,l;

inline void swap(int x,int y)
{
    int a=H[x],b=H[y],aux;
    H[y]=a;
    H[x]=b;
    aux=poz[a];
    poz[a]=poz[b];
    poz[b]=aux;
    return;
}

//Heap-Down, folosit pentru a sterge un element deja existent in heap

inline void Heap_Down(int x,int l_max)
{
    int f_st=x*2,f_dr=x*2+1,St,Dr;
    if (f_st>l_max) return;
    St=V[H[f_st]];
    if (f_dr<=l_max) Dr=V[H[f_dr]];
            else Dr=St+1;
    if (St<Dr)
        {
            swap(f_st,x);
            Heap_Down(f_st,l_max);
        }
        else
            {
                swap(f_dr,x);
                Heap_Down(f_dr,l_max);
            }
}

//Heap-Up, folosit pentru a introduce un nou element in heap

inline void Heap_Up(int x)
{
    if (x==1) return;
    int t=x/2;
    if (V[H[x]]<V[H[t]])
        {

            swap(x,t);
            Heap_Up(t);
        }

}

//citirea comenzilor

inline void Load_Data(int &k,int &x)
{
    char s[30];
    int n,i;
    gets(s);
    n=strlen(s);
    k= s[0]-48;
    if (n==1) return;
    for (i=2;i<n;++i)
        x=x*10 + ( s[i]-48 );
    return;
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d\n",&N);
    l=0;
    for(i=1;i<=N;i++)
    {
        k=0;
        x=0;
        Load_Data(k,x);
        if (k==1)
            {
                //INSERAREA ELEMENTULUI
                V[++l]=x;
                poz[l]=l;
                H[l]=l;
                Heap_Up(l);
            }
        if (k==2)
            {
                //STERGEREA ELEMENTULUI
                int p=poz[x];
                swap(l,p);
                l--;
                if (V[H[p]]>V[H[p/2]] && p!=1) Heap_Up(p);
                    else Heap_Down(p,l);
            }
        if (k==3)
            {
                //AFISAREA REZULTULUI
                printf("%d\n",V[H[1]]);
            }
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}