Cod sursa(job #2429870)

Utilizator ela_topaTopa Elena ela_topa Data 11 iunie 2019 17:18:58
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include<bits/stdc++.h>
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
constexpr int NX = 200010;
int N, cateSunt, bonOrdine;
//in ordine tin indicii din heap in ordinea din heap
//ex 1 2 3 4
//   1 2 3 4
vector < pair <int, int> > heap;
int ordine[NX];
void urca(int l_poz)
{
    int father = l_poz/2;
    if(father && heap[l_poz].first < heap[father].first)
    {
        swap(heap[l_poz], heap[father]);
        swap(ordine[heap[l_poz].second], ordine[heap[father].second]);
        urca(father);
    }
}
void coboara(int l_poz)
{
    int son = l_poz*2; //son_right e son+1
    if(son+1<=heap.size()-1 && heap[son].first > heap[son+1].first) //daca ala dn dreapta e mai mare
        son++; //e fiul din dreapta
    if(son<=heap.size() && heap[l_poz].first > heap[son].first)
    {
        swap(heap[l_poz], heap[son]);
        swap(ordine[heap[l_poz].second], ordine[heap[son].second]);
        coboara(son);
    }
}

void insertHeap(int x)
{
    heap.push_back({x, bonOrdine}); //il bag in heap impreuna cu nr la rand
    ordine[bonOrdine] = heap.size()-1; //fac elementul din vectorul de pozitii al catelea e
    urca(heap.size()-1);
}

void deleteHeap(int who)
{
    int poz = ordine[who]; //poz e pozitia de pe care sterg
    heap[poz].first = heap[heap.size()-1].first; //in locul lui vine ala de pe ultima poz
    heap[poz].second = heap[heap.size()-1].second;
    ordine[heap[poz].second] = poz;
    heap.pop_back(); //il scot
    int father = poz/2;
    //urc sau cobor in fct de ce trb
    if(poz>0 && heap[poz].first < heap[father].first)
        urca(poz);
    else
        coboara(poz);

}

int main()
{
    fin>>N;
    int tip, x;
    for(int i=1; i<=N; ++i)
    {
        fin>>tip;
        if(tip == 1)
        {
            fin>>x;
            bonOrdine++; //aici e ordinea cronologica a fiecarui nr
            insertHeap(x);
        }
        else if(tip == 2)
        {
            fin>>x;
            //x e pozitia din ordine a nr pe care trb sa il sterg
            deleteHeap(x);

        }
        else if(tip == 3)
        {
            fout<<heap[0].first<<"\n";
        }
    }
    return 0;
}