Cod sursa(job #1001963)

Utilizator ThomasFMI Suditu Thomas Thomas Data 26 septembrie 2013 17:24:09
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <cstdlib>
using namespace std;

#define Nmax 200001

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int H[Nmax],poz[Nmax],n;
int op,i,a,b,j;

void perc(int x) //percolate
{
    int xx=x/2;
    while(x!=1 && H[x]<H[xx])
    {
        swap(H[x],H[xx]);
        swap(poz[x],poz[xx]);
        x=xx;
        xx=x/2;
    }
}

void sift(int x)
{
    int nn=n/2,xx=x*2,xy=xx+1,son=1;
    while(x<=nn && son)
    {
        if(H[x]>H[xx]) son=xx;
        if(H[xx]>H[xy]) son=xy;
        swap(H[x],H[son]);
        swap(poz[x],poz[son]);
        x=son;
        xx=x*2;
        xy=xx+1;
        son=0;
    }
}

void ins(int x)
{
    H[++n]=x;
    poz[n]=n;
    perc(n);
}

void sterg(int x)
{
    H[x]=H[n];
    poz[x]=poz[n];
    n--;
    if(H[x]<H[x/2]) perc(x);
    else sift(x);
}

void minim()
{
    g<<H[1]<<"\n";
}

int srch(int x)
{
    for(int i=1;i<=n;i++) if(poz[i]==x) return i;
}

int main()
{
    f>>op;
    for(i=1;i<=op;i++)
    {
        f>>a;
        if(a==1) {f>>b; ins(b);}
        else if(a==2) {f>>b; sterg(srch(b));}
        else minim();
    }

    f.close();
    g.close();
    return 0;
}