Cod sursa(job #774411)

Utilizator gicu_01porcescu gicu gicu_01 Data 4 august 2012 16:51:04
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <stdio.h>
#define nmax 200001
using namespace std;
int n,m,Poz[nmax],npoz;

struct nod{
   int x;
   int y;
} H[nmax];

void sw(nod *a,nod *b)
{
    nod t=*a; *a=*b; *b=t;
}

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

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

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

void up(int nod)
{
    int k=H[nod].x;
    int p=H[nod].y;
    int t;
    while (father(nod)>=1 && H[father(nod)].x>k)
    {
        t=father(nod);
        H[nod].x=H[t].x;
        H[nod].y=H[t].y;
        Poz[H[nod].y]=nod;
        nod=nod/2;
    }
    H[nod].x=k;
    H[nod].y=p;
    Poz[p]=nod;
}

void down(int nod)
{
    int k=H[nod].x;
    int p=H[nod].y;
    int son,c,t=1;
    while (H[nod*2].x && t  && nod*2<=n)
    {
        t=0;
        son=l_son(nod); c=1;
        if (H[r_son(nod)].x && H[r_son(nod)].x<H[son].x && r_son(nod)<=n) { son=r_son(nod); c=0; }
        if (H[son].x<k){
            H[nod].x=H[son].x;
            H[nod].y=H[son].y;
            Poz[H[nod].y]=nod;
            if (c) nod=nod*2; else nod=nod*2+1;
            t=1;
        }
    }
    H[nod].x=k;
    H[nod].y=p;
    Poz[p]=nod;
}

void add(int val)
{
    n++; npoz++;
    H[n].x=val;
    H[n].y=npoz;
    Poz[npoz]=npoz;
    up(n);
}

void cut(int x)
{
    int t=Poz[x];
    sw(&H[Poz[x]],&H[n]);
    n--;
    up(t);
    down(t);
}

int main()
{
    int i,j,b,k;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%i",&m);
    for (i=1; i<=m; i++)
    {
        scanf("%i",&j);
        if (j==1) {
            scanf("%i",&b);
            add(b);
        }else
        if (j==2) {
            scanf("%i",&b);
            cut(b);

        } else printf("%i\n",H[1].x);
    }
    return 0;
}