Cod sursa(job #1415633)

Utilizator alex1096Postolache Alex alex1096 Data 5 aprilie 2015 16:29:57
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
using namespace std;
const int N = 200000;

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

int h[N], v[N], poz[N], nrh, nre;

void schimb(int x, int y)
{
    int aux = h[x];

    h[x] = h[y];
    h[y] = aux;

    poz[h[x]] = x;
    poz[h[y]] = y;
}

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

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, bun = p;

    if (fs <= nrh && v[h[fs]] < v[h[bun]]) bun = fs;

    if (fd <= nrh && v[h[fd]] < v[h[bun]]) bun = fd;
    if (bun != p)
    {
        schimb(p, bun);
        coboara(bun);
    }
}

void afisare()
{
    for(int i=1;i<=nrh;i++)
        g<<v[h[i]]<<" ";
    g << "\n";
}
int main()
{
    int n, op,x;
    f>>n;
    for(int i=1; i<=n; i++)
    {
        f>>op;
        if(op == 1)
        {
            f>>x;
            v[++nre] = x;
            h[++nrh] = nre;
            poz[h[nrh]] = nrh;
            urca(nrh);
        }
        else if(op == 2)
        {
            f>>x;
            x = poz[x];
            schimb(x, nrh--);
            urca(x);
            coboara(x);
        }
        else g<<v[h[1]]<<'\n';

    }
    return 0;
}