Cod sursa(job #2773814)

Utilizator iustin.pericicaPericica Iustin iustin.pericica Data 8 septembrie 2021 19:27:19
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int heap[400001];
int pozitieInHeapPeBazaIntrariiInHeap[200001];
int numere[200001];
int no;

void urcaNod(int heap[], int n, int k){

    int valoare = numere[heap[k]];

    while(k/2 && valoare < numere[heap[k/2]]){
        swap(heap[k], heap[k/2]);
        pozitieInHeapPeBazaIntrariiInHeap[heap[k]] = k;
        pozitieInHeapPeBazaIntrariiInHeap[heap[k/2]] = k/2;

        k = k/2;

    }

}

void sift(int heap[], int n, int k) {
    int son;
    do {
        son = 0;
        // Alege un fiu mai mic ca tatal.
        if (k*2 <= n) {
            son = k*2;;
            if (k*2+1 <= n && numere[heap[k*2+1]] < numere[heap[k*2]]) {
                son = k*2+1;
            }
            if (numere[heap[son]] >= numere[heap[k]]) {
                son = 0;
            }
        }

        if (son) {
            swap(heap[k], heap[son]);
            pozitieInHeapPeBazaIntrariiInHeap[heap[son]] = son;
            pozitieInHeapPeBazaIntrariiInHeap[heap[k]] = k;
            k = son;
        }
    } while (son);
}



void inserare(int heap[], int &n, int val, int &nr){

    ++n;
    ++nr;
    heap[n] = nr;
    pozitieInHeapPeBazaIntrariiInHeap[nr] = n;

    numere[nr] = val;
    urcaNod(heap, n, n);

}

void stergere(int heap[], int &n, int k){

    heap[k] = heap[n];
    --n;


    sift(heap, n, k);


}



int main()
{
    fin>>no;
    int n = 0;
    int nr = 0;
    for(int i = 1;i<=no;++i){
        int o, v;
        fin>>o;
        if(o == 1){
            //inserare
            fin>>v;
            inserare(heap, n, v, nr);
        }
        else if(o == 2){
            fin>>v;
            stergere(heap, n, pozitieInHeapPeBazaIntrariiInHeap[v]);
        }
        else{
            fout<<numere[heap[1]]<<"\n";
        }
    }
    return 0;
}