Cod sursa(job #2773810)

Utilizator iustin.pericicaPericica Iustin iustin.pericica Data 8 septembrie 2021 19:04:34
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 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]];
    int poz = heap[k];

    while(k > 1 && 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){

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

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

}

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

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

    if ((k > 1) && (numere[heap[k]] < numere[heap[k/2]])) {
        urcaNod(heap, n, k);
    } else {
        sift(heap, n, k);
    }

}



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