Cod sursa(job #2815208)

Utilizator CristeaCristianCristea Cristian CristeaCristian Data 9 decembrie 2021 12:00:11
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector <int> heap(1, 0), poz(1, 0), v(1, 0);
int k;
const int NMAX = 200005;
bool empty()
{
    return (heap.size() == 1);
}
void insert(int x)
{
    int pos = heap.size();
    heap.push_back(++k);
    v.push_back(x);
    poz.push_back(pos);
    while(pos > 1)
    {
        if(v[heap[pos]] < v[heap[pos / 2]])
        {
            swap(heap[pos], heap[pos / 2]);
            swap(poz[heap[pos]], poz[heap[pos / 2]]);
        }
        else
            break;
        pos = pos / 2;
    }
}
void pop(int x)
{
    int pos = poz[x], ok = 1, aux;
    aux = heap[heap.size() - 1];
    swap(heap[pos], heap[heap.size() - 1]);
    swap(poz[x], poz[heap[heap.size() - 1]]);
    poz[heap[heap.size() - 1]] = 0;
    heap.pop_back();
    aux = pos;
    while(pos > 1)
    {
        if(v[heap[pos]] < v[heap[pos / 2]])
        {
            swap(heap[pos], heap[pos / 2]);
            swap(poz[heap[pos]], poz[heap[pos / 2]]);
            ok = 0;
        }
        else
            break;
        pos = pos / 2;
    }
    pos = aux;
    if(ok)
    {
        int pos_min;
        while(pos * 2 < heap.size())
        {
            pos_min = 2 * pos;
            if(2 * pos + 1 < heap.size() && v[heap[pos_min]] > v[heap[pos * 2 + 1]])
                pos_min = 2 * pos + 1;
            if(v[heap[pos]] <= v[heap[pos_min]])
                break;
            swap(heap[pos], heap[pos_min]);
            swap(poz[heap[pos]], poz[heap[pos_min]]);
            pos = pos_min;
        }
    }
}
int top()
{
    return v[heap[1]];
}
int main()
{
    int m, i, op, x;
    fin >> m;
    while(m--)
    {
        fin >> op;
        if(op == 1)
        {
            fin >> x;
            insert(x);
        }
        else if(op == 2)
        {
            fin >> x;
            pop(x);
        }
        else
        {
            fout << top() << '\n';
        }
    }
    return 0;
}