Cod sursa(job #1768403)

Utilizator raresm44vasile rares raresm44 Data 30 septembrie 2016 20:31:25
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
using namespace std;

const int N = 200001;

int nh,h[N],v[N], poz[N], nr, n;

void schimba(int a,int b)
{
    int c=h[a];
    h[a]=h[b];
    h[b]=c;
    poz[h[a]] = a;
    poz[h[b]] = b;
}

void coboara(int p)
{
    int fs=2*p,fd=2*p+1,bun=p;
    if(fs<=nh && v[h[fs]] < v[h[bun]]) bun=fs;
    if(fd<=nh && v[h[fd]] < v[h[bun]]) bun=fd;
    if(bun!=p)
    {
        schimba(bun,p);
        coboara(bun);
    }

}

void urca(int p)
{
    while(p!=1 && v[h[p]] < v[h[p/2]])
    {
        int c=p/2;
        schimba(p,c);
        p/=2;
    }
}

void adauga(int p)
{
    nh++;
    h[nh]=p;
    poz[p] = nh;
    urca(nh);
}

void sterge(int p)
{
    schimba(p,nh--);
    urca(p);
    coboara(p);
}

int main()
{
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    //cout << "Hello world!" << endl;
    f>>n;
    int i=0, a, b, m;
    while(i!=n)
    {
        f>>b;
        if(b==1)
        {
            f>>a;
            v[++nr] = a;
            adauga(nr);
        }
        else if(b==2)
        {
            f>>a;
            sterge(poz[a]);
        }
        else
            g<<v[h[1]]<<"\n";
        i++;
    }

    /*n=0;
    cout<<endl;
    while(nh!=0)
    {
        cout<<h[1]<<' ';
        v[++n]=h[1];
        sterge(1);
    }*/
    return 0;
}