Cod sursa(job #1385816)

Utilizator andru47Stefanescu Andru andru47 Data 12 martie 2015 13:49:45
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
#include <algorithm>
#define val first
#define poz second
using namespace std;
pair <int,int> a[500005];
int N,instr,x,fi[500005],n,i,nr,xx;
inline void swapp(int poz1,int poz2)
{
    swap(a[poz1].val,a[poz2].val);
    swap(a[poz1].poz,a[poz2].poz);
    swap(fi[a[poz1].poz],fi[a[poz2].poz]);
    return ;
}
inline void heapup(int poz)
{
    if(n<=1)return ;
    if (a[poz].val<a[poz/2].val)
    {
        swapp(poz,poz/2);
        heapup(poz/2);
    }
    return ;
}
inline void heapdown(int poz)
{
    int x1,x2;
    if (2*poz<=n)
    {
        x1=a[2*poz].val;
        if (2*poz+1>n)x2=x1+1;
        else x2=a[2*poz+1].val;
        if (x1<=x2)
        {
            swapp(2*poz,poz);
            heapdown(2*poz);
        }
        else
        {
            swapp(2*poz+1,poz);
            heapdown(2*poz+1);
        }
    }
    return ;
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d\n",&N);
    for (i=1;i<=N;i++)
    {
        scanf("%d",&instr);
        if (instr==1)
        {
            scanf(" %d",&x);
            nr++;
            a[++n].val=x;
            a[n].poz=nr;
            fi[nr]=n;
            heapup(n);
        }
        else if (instr==2)
        {
            scanf(" %d",&x);
            xx=fi[x];
            swapp(fi[x],n);
            --n;
            heapdown(xx);
        }
        else
        {
            printf("%d\n",a[1].val);
        }
    }
    return 0;
}