Cod sursa(job #2745542)

Utilizator almar.fetaFeta Almar almar.feta Data 26 aprilie 2021 18:06:39
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n,x,y;
int len;
int heap[200000];
int l;
int pos[200001];

void push(int x)
{
    heap[len] = x;
    pos[len++] = ++l;

    int poz = len - 1;
    while(poz)
    {
        int tata = (poz-1)/2;
        if(heap[tata] > heap[poz])
        {
            swap(heap[tata],heap[poz]);
            swap(pos[tata],pos[poz]);
            poz = tata;
        }
        else
            break;
    }
}

void coboara(int poz)
{
    if (poz * 2 + 1 >= len)
        return;
    int fiu_st = heap[poz * 2 + 1];
    if((poz * 2 + 2 == len) || fiu_st > heap[poz * 2 + 2])
        if (fiu_st < heap[poz])
        {
            swap(heap[poz], heap[poz * 2 + 1]);
            swap(pos[poz],pos[poz*2+1]);
            coboara(poz * 2 + 1);
            return;
        }
        else
            return;
    else
        if (heap[poz * 2 + 2] < heap[poz])
        {
            swap(heap[poz], heap[poz * 2 + 2]);
            swap(pos[poz], pos[poz * 2 + 2]);
            coboara(poz * 2 + 2);
            return;
        }
        else
            return;
}

void pop(int x)
{
    int poz;
    for(int i=0; i<len; i++)
        if(pos[i] == x)
            {poz = i; break;}
    heap[poz] = heap[len-1];
    pos[poz] = pos[len-1];
    len--;

    int tata = (poz-1)/2;
    if(heap[poz] < heap[tata] && poz != 0)
        while(poz)
        {
            tata = (poz-1)/2;
            if(heap[tata] > heap[poz])
            {
                swap(heap[tata],heap[poz]);
                swap(pos[tata],pos[poz]);
                poz = tata;
            }
            else
                break;
        }
    else
        coboara(poz);
}

int main()
{
    in >> n;
    for(int i=1; i<=n; i++)
    {
        in >> x;
        if(x == 1 || x == 2)
            in >> y;

        if(x == 1)
            push(y);
        else if(x == 2)
            pop(y);
        else if(x == 3)
            out << heap[0] << "\n";
    }

    in.close();
    out.close();
    return 0;
}