Cod sursa(job #1812948)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 22 noiembrie 2016 16:20:12
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <stdio.h>

const int nmax=200001;
int V[nmax];
int H[nmax];
int L[nmax];

inline int father(int nod)
{
    return nod/2;
}

inline int lefts(int nod)
{
    return nod*2;
}

inline int rights(int nod)
{
    return nod*2+1;
}

void up(int pos)
{
    int aux;

    while (father(pos) && V[H[pos]]<V[H[father(pos)]])
    {
        aux=H[pos];
        H[pos]=H[father(pos)];
        H[father(pos)]=aux;

        L[H[pos]]=pos;
        L[H[father(pos)]]=father(pos);
        pos=father(pos);
    }
}

void down(int sz,int pos)
{
    int son;

    do
    {
        son=0;

        int ls=lefts(pos);
        if (ls <= sz)
            son=ls;
        int rs=rights(pos);
        if (rs <= sz && V[H[ls]]>V[H[rs]])
            son=rs;
        if (V[H[son]] >= V[H[pos]])
            son=0;

        if (son)
        {
            int aux=H[son];
            H[son]=H[pos];
            H[pos]=aux;
            L[H[son]]=son;
            L[H[pos]]=pos;

            pos=son;
        }
    }
    while(son);
}

void insert(int &sz, int x)
{
    H[++sz]=x;
    up(sz);
}

void del(int &sz, int pos)//sz,pos(x)
{
    H[pos]=H[sz];
    L[H[pos]]=pos;
    sz--;

    if (father(pos) && V[H[pos]] < V[H[father(pos)]])
        up(pos);
    else
        down(sz,pos);
}

int main()
{
    FILE *fi,*fo;
    int n,key,x,i,j,sz;

    fi=fopen("heapuri.in","r");
    fo=fopen("heapuri.out","w");
    fscanf(fi,"%d",&n);
    sz=j=0;

    for (i=1; i<=n; i++)
    {
        fscanf(fi,"%d",&key);
        if (key == 1)
        {
            fscanf(fi,"%d",&x);
            ++j;
            V[j]=x;///a j-ua valoare
            L[j]=sz+1;///pozitia celei dea j-a valori
            insert(sz,j);
        }
        if (key == 2)
        {
            fscanf(fi,"%d",&x);
            del(sz,L[x]);
        }
        if (key == 3)
        {
            fprintf(fo,"%d\n",V[H[1]]);
        }
    }
    fclose(fi);
    fclose(fo);
}