Cod sursa(job #1043515)

Utilizator vlady1997Vlad Bucur vlady1997 Data 28 noiembrie 2013 18:13:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
        #include <cstdio>
        using namespace std;
        int a[200001], h[200001], poz[200001], m=0, n=0;
        void Swap (int i, int j)
        {
            int aux;
            aux=h[i]; h[i]=h[j]; h[j]=aux;
            poz[h[i]]=i; poz[h[j]]=j;
        }
        void push (int p)
        {
            int i, st, dr;
            bool ok=false;
            if (a[h[p]]<a[h[p/2]] && p/2>0)
            {
                while (ok==false && p/2>0)
                {
                    if (a[h[p]]<a[h[p/2]]) {Swap(p,p/2); p=p/2;}
                    else ok=true;
                }
            }
        }
        void del (int p)
        {
            int i, st, dr;
            bool ok=false;
            Swap(p,n); n--;
            if (p*2<=n)
            {
                while (ok==false && i*2<=n)
                {
                    st=a[h[p*2]];
                    if(2*p+1<=n) dr=a[h[2*p+1]];
                    else dr=st+1;
                    if(st<dr) i=2*p;
                    else i=2*p+1;
                    if (a[h[p]]>a[h[i]]) {Swap(i,p);}
                    else ok=true;
                }
            }
        }
        int main()
        {
            int i, t, x, z, p;
            freopen("heapuri.in","r",stdin);
            freopen("heapuri.out","w",stdout);
            scanf("%d",&t);
            for (i=1; i<=t; i++)
            {
                scanf("%d",&z);
                if (z==1)
                {
                    scanf("%d",&x);
                    a[++m]=x; h[++n]=n; poz[m]=n;
                    push(n);
                }
                else if (z==2)
                {
                    scanf("%d",&p); del(poz[p]);
                }
                else if (z==3)
                {
                    printf("%d\n",a[h[1]]);
                }
            }
            fclose(stdin);
            fclose(stdout);
            return 0;
        }