Cod sursa(job #1641501)

Utilizator secretCCMniciun nume secretCCM Data 8 martie 2016 23:46:00
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>

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

const int Nmax = 200005;
int n, pos[Nmax], heap[Nmax], a[Nmax], nheap, m;

void Swap(int c, int b)
{
    swap(heap[c],heap[b]);
    swap(pos[heap[c]],pos[heap[b]]);
}

void Downheap(int nod)
{
    int fiu = nod*2;
    if(fiu > nheap) return;
    if(fiu == nheap && a[heap[fiu]] < a[heap[nod]])
    {
        Swap(fiu, nod);
        return;
    }
    if(a[heap[fiu]] < a[heap[fiu + 1]])
    {
        if(a[heap[fiu]] < a[heap[nod]])
        {
            Swap(fiu, nod);
            Downheap(fiu);
        }
    }
    else
    {
        if(a[heap[fiu+1]] < a[heap[nod]])
        {
            Swap(fiu+1, nod);
            Downheap(fiu+1);
        }
    }
}

void Upheap(int nod)
{
    int tata = nod/2;
    if(a[heap[tata]] > a[heap[nod]] && tata)
    {
        Swap(tata,nod);
        Upheap(tata);
    }
}

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