Cod sursa(job #1320566)

Utilizator claudiu.gatinaFMI Claudiu Gatina claudiu.gatina Data 18 ianuarie 2015 02:29:34
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <cstdio>
#include <algorithm>
#define maxn 500001
#define numberlimit 10000001

using namespace std;
long long int v[maxn],poz[maxn],sum;
int nv,nh,a,i,x,h[maxn],k;

void percolate(int n)
{
    while (n/2 && v[h[n]]<v[h[n/2]])
    {
        swap(poz[h[n]], poz[h[n/2]]);
        swap(h[n], h[n/2]);
        n/=2;
    }
}

void sift(int n)
{
    while(n<=nh/2)
    {
        if(v[h[n]]>v[h[2*n]] || v[h[n]]>v[h[2*n+1]])
        {
            if(v[h[2*n]]<v[h[2*n+1]])
            {
                swap(poz[h[n]], poz[h[2*n]]);
                swap(h[n],h[2*n]);
                n*=2;
            }
            else
            {
                swap(poz[h[n]], poz[h[2*n+1]]);
                swap(h[n],h[2*n+1]);
                n=2*n + 1;
            }
        }
        else return;
    }
}

void deletee(int n)
{
    poz[h[nh]]=poz[n];
    h[poz[n]]=h[nh];
    nh--;
    if(poz[n]>1 && v[h[poz[n]]]<v[h[poz[n]/2]])
        percolate(poz[n]);
    else
        sift(poz[n]);
}

inline void insertt(int x)
{
    nh++;
    nv++;
    v[nv]=x;
    h[nh]=nv;
    poz[nv]=nh;
    percolate(nh);
}

void afisare()
{
    for(int t=1;t<=nh;t++)
        printf("%d ", v[h[t]]);
    printf("\n");
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int n,j;
    v[0]=numberlimit;
    scanf("%d ", &n);
    for (i=1;i<=n;i++)
    {
        scanf("%d ", &a);
        if (a==3)
            printf("%d\n", v[h[1]]);
        else
        {
            scanf("%d ", &x);
            if (a==1)
            {
                insertt(x);
            }
            if (a==2)
                deletee(x);
        }
    }
}