Cod sursa(job #1648758)

Utilizator cordun_cristinaCristina Maria Cordun cordun_cristina Data 11 martie 2016 11:32:46
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>

using namespace std;
#include <iostream>
#include <fstream>

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

const int Nmax = 200005;
int n, m, nheap, pos[Nmax], M[Nmax], Heap[Nmax];

void Swap(int a, int b)
{
    swap(Heap[a], Heap[b]);
    swap(pos[Heap[a]], pos[Heap[b]]);
}

void Upheap(int nod)
{
    int tata = nod/2;
    if(tata && M[Heap[nod]] < M[Heap[tata]])
    {
        Swap(tata,nod);
        Upheap(tata);
    }
}

void Downheap(int nod)
{
    int son = 2*nod;
    if(son > nheap) return;
    if(son == nheap && M[Heap[nod]] > M[Heap[son]])
    {
        Swap(nod,son);
        return;
    }
    if(M[Heap[son]] > M[Heap[son+1]])
    {
        if(M[Heap[nod]] > M[Heap[son+1]])
        {
            Swap(nod, son+1);
            Downheap(son+1);
        }
    }
    else
    {
        if(M[Heap[nod]] > M[Heap[son]])
        {
            Swap(nod, son);
            Downheap(son);
        }
    }
}

int main()
{
    f>>n;
    while(n--)
    {
        int opt, x;
        f>>opt;
        if(opt == 1)
        {
            f>>x;
            M[++m] = x;
            Heap[++nheap] = m;
            pos[m] = nheap;
            Upheap(nheap);
        }
        if(opt == 2)
        {
            f>>x;
            int poz = pos[x];
            Swap(poz,nheap--);
            Downheap(poz);
        }
        if(opt == 3) g<<M[Heap[1]]<<'\n';
    }
    return 0;
}