Cod sursa(job #2689851)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 22 decembrie 2020 14:58:36
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int nr_elem, nr_ordine;
bool verif[200005];

struct heap{
    int val, ord;
} v[200005];

void insertHeap(int nr)
{
    nr_elem++;
    nr_ordine++;
    v[nr_elem].val=nr;
    v[nr_elem].ord=nr_elem;
    int poz=nr_elem;
    while(v[poz].val < v[poz/2].val && poz>=2)
    {
        swap(v[poz], v[poz/2]);
        poz/=2;
    }
}

void popHeap()
{
    v[1]=v[nr_elem];
    nr_elem--;
    int poz=1;
    while(poz*2 <=nr_elem &&(v[poz].val > v[poz*2].val || v[poz].val > v[poz*2+1].val))
    {
        if(v[poz*2].val <= v[poz*2+1].val)
        {
            swap(v[poz], v[poz*2]);
        }
        else
        {
            swap(v[poz], v[poz*2+1]);
        }
    }
}

int topHeap()
{
    bool ok=0;
    while(!ok)
    {
        heap top=v[1];
        if(verif[top.ord])
        {
            ok=1;
            return top.val;
        }
        else
        {
            popHeap();
        }

    }
}

int main()
{
    int nr_operatii;
    fin>>nr_operatii;
    for(int operatie=1; operatie<=nr_operatii; operatie++)
    {
        int task,nr;
        fin>>task;
        if(task==1)
        {
            fin>>nr;
            insertHeap(nr);
            verif[nr_ordine]=true;
        }
        if(task==2)
        {
            fin>>nr;
            verif[nr]=false;
        }
        if(task==3)
        {
            nr=topHeap();
            fout<<nr<<'\n';
        }
    }
    return 0;
}