Cod sursa(job #1190021)

Utilizator RRomaniucRomaniuc Radu Andrei RRomaniuc Data 24 mai 2014 12:22:56
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <stdio.h>
using namespace std;
struct mystruct{ int pos, val;};
mystruct v[200001],h[200001],aux;
int nv,nh=0,n;
void scoatere(int pozitie)
{
    int ind = v[pozitie].pos;
    v[pozitie].pos = -1;
    h[ind] = h[nh]; nh--;
    v[h[ind].pos].pos = ind;

    int i = ind;
    while(h[i].val < h[i/2].val && i > 1)
    {
        aux=h[i];
        h[i]=h[i/2];
        h[i/2]=aux;

        v[h[i].pos].pos=i;
        v[h[i/2].pos].pos=i/2;

        i=i/2;
    }

    int pozfiu;
    while((h[i].val > h[i*2].val||h[i].val > h[i*2+1].val) && i*2 < nh)
    {
        pozfiu = 2*i;
        if(h[2*i+1].val<h[2*i].val)pozfiu++;

        aux=h[pozfiu];
        h[pozfiu]=h[i];
        h[i]=aux;

        v[h[i].pos].pos=i;
        v[h[pozfiu].pos].pos=pozfiu;

        ind = pozfiu;
    }

    if((nh == i*2)&&(h[i].val>h[nh].val))
    {
        pozfiu = nh;
        aux=h[pozfiu];
        h[pozfiu]=h[i];
        h[i]=aux;

        v[h[i].pos].pos=i;
        v[h[pozfiu].pos].pos=pozfiu;
    }

}
void adaugare(int x)
{
    nv++;
    v[nv].val=x;

    nh++;
    h[nh].val=x;

    v[nv].pos=nh;
    h[nh].pos=nv;

    int i=nh;
    while(h[i].val < h[i/2].val && i > 1)
    {
        aux=h[i];
        h[i]=h[i/2];
        h[i/2]=aux;

        v[h[i].pos].pos=i;
        v[h[i/2].pos].pos=i/2;

        i=i/2;
    }
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    int tip,x,i;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&tip);
        if(tip==3)printf("%d \n",h[1].val);
        else
        {
            scanf("%d",&x);
            if(tip==1)adaugare(x);
            else scoatere(x);
        }
    }

    return 0;

}