Cod sursa(job #1001987)

Utilizator ThomasFMI Suditu Thomas Thomas Data 26 septembrie 2013 17:57:43
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 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,nr;
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 xx=x*2,xy=xx+1,son;
    do
    {
        son=0;
        if(H[x]>H[xx] && xx<=n) son=xx;
        if(H[xx]>H[xy] && xy<=n) son=xy;
        if(son)
        {
            swap(H[x],H[son]);
            swap(poz[x],poz[son]);
            x=son;
            xx=x*2;
            xy=xx+1;
        }
    } while(son);
}

void ins(int x)
{
    H[++n]=x;
    poz[n]=++nr;
    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();

        /*if(a!=3)
        {
            g<<a<<" "<<b<<"\n";
            for(j=1;j<=n;j++) g<<H[j]<<" ";
            g<<"\n\n";
        }
        else
        {
            g<<a<<"\n";
            for(j=1;j<=n;j++) g<<H[j]<<" ";
            g<<"\n\n";
        }*/

    }

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