Cod sursa(job #1011862)

Utilizator Stefanescu_MihaiStefanescu Mihai-Nicolae Stefanescu_Mihai Data 17 octombrie 2013 17:42:16
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <cstdio>
using namespace std;
int n,v[200010],poz[200010],p,ran[200010];
void swap(int x,int y)
{
    int t=v[x];
    v[x]=v[y];
    v[y]=t;
    poz[ran[x]]=y;
    poz[ran[y]]=x;
    t=ran[x];
    ran[x]=ran[y];
    ran[y]=t;
}
void upsift(int k)
{
    if ((v[k]<v[k/2])&&(k>1))
    {
        swap(k,k/2);
        upsift(k/2);
    }
}
void downsift(int k)
{
    if (k*2>n)
        return;
    if (v[k]>v[k*2])
    {
        if ((v[k*2]>v[k*2+1])&&(k*2<n))
        {
            swap(k,k*2+1);
            downsift(k*2+1);
        }
        else
        {
            swap(k,k*2);
            downsift(k*2);
        }
    }
    else
        if ((v[k]>v[k*2+1])&&(k*2<n))
        {
            swap(k,k*2+1);
            downsift(k*2+1);
        }
}
void remove(int k)
{
    int t=v[k];
    swap(k,n);
    --n;
    if (v[k]>t)
        downsift(k);
    else
        upsift(k);
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int i,m,t;
    char c;
    scanf("%d\n",&m);
    for (i=1;i<=m;++i)
    {
        scanf("%c",&c);
        if (c=='3')
        {
            printf("%d\n",v[1]);
            scanf("\n");
            continue;
        }
        else
        {
            if (c=='1')
            {
                scanf(" %d\n",&v[++n]);
                poz[++p]=n;
                ran[n]=p;
                upsift(n);
                continue;
            }
            else
                if (c=='2')
                {
                    scanf(" %d\n",&t);
                    remove(poz[t]);
                    continue;
                }
        }
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}