Cod sursa(job #2890478)

Utilizator madalin1907Florea Madalin Alexandru madalin1907 Data 15 aprilie 2022 17:38:59
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>
using namespace std;

struct Element{
    int value,index;
};

vector <Element> heap;
int aux[200010];


void swapn(int poz1, int poz2)
{
    swap(heap[poz1],heap[poz2]);
    swap(aux[heap[poz1].index],aux[heap[poz2].index]);
}


int main() {
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    Element first;
    heap.push_back(first);
    int n, k = 0;
    fin >> n;
    while(n--)
    {
        int operatie;
        fin >> operatie;
        if(operatie == 1)
        {
            int x;
            fin >> x;
            k++;
            Element current;
            current.value = x;
            current.index = k;
            heap.push_back(current);
            aux[current.index] = heap.size() - 1;
            int a = heap.size() - 1;
            while(a != 1 and heap[a].value < heap[a / 2].value) {
                swapn(a,a / 2);
                a /= 2;
            }
        }

        if(operatie == 2)
        {
            int index;
            fin >> index;
            int position = aux[index];
            swapn(position, heap.size() - 1);
            heap.pop_back();
            while(position != 1 and heap[position].value < heap[position / 2].value) {
                swapn(position,position / 2);
                position /= 2;
            }
            while(2 * position < heap.size())
            {
                if(2 * position + 1 >= heap.size() or heap[2 * position].value < heap[2 * position + 1].value)
                {
                    if(heap[position].value > heap[2 * position].value)
                    {
                        swapn(position, 2 * position);
                        position *= 2;
                    }
                    else break;
                }
                else
                {
                    if(heap[position].value > heap[2 * position + 1].value)
                    {
                        swapn(position, 2 * position + 1);
                        position *= 2;
                        position ++;
                    }
                    else break;
                }
            }
        }

        if(operatie == 3)
        {
            fout << heap[1].value << "\n";
        }
    }
    return 0;
}