Cod sursa(job #2740666)

Utilizator ChelaruPaulChelaru Paul ChelaruPaul Data 13 aprilie 2021 19:37:09
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
using namespace std;

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

int heap[200001], nr[200001], pos[200001];
int nrActiuni, actiune, nrElem = 0;

int father(int nod){
    return nod / 2;
}

int left_son(int nod){
    return 2 * nod;
}

int right_son(int nod){
    return 2 * nod + 1;
}

void percolate(int nod){
    int key = heap[nod];

    while((nod > 1) and (key < heap[father(nod)])){
        heap[nod] = heap[father(nod)];
        pos[heap[father(nod)]] = nod;
        nod = father(nod);
    }

    heap[nod] = key;
    pos[key] = nod;
}

void shift(int nod){
    int son;
    do{
        son = 0;
        if(left_son(nod) <= nrElem){
            son = left_son(nod);
            if(right_son(nod) <= nrElem and heap[right_son(nod)] < heap[left_son(nod)]){
                son = right_son(nod);
            }
        }

        if(heap[son] >= heap[nod]){
            son = 0;
        }

        if(son){
            swap(heap[nod], heap[son]);
            swap(pos[heap[son]], pos[heap[nod]]);
            nod = son;
        }
    }while (son);
}

void deleteElem(int nod){
    heap[nod] = heap[nrElem];
    nrElem --;

    if(nod > 1 and heap[nod] < heap[father(nod)]) percolate(nod);
    else shift(nod);
}

int main(){
    fin  >> nrActiuni;
    for(int i = 0; i < nrActiuni; i ++) {
        fin >> actiune;
        if (actiune == 1) {
            int elem;
            fin >> elem;

            nr[++nrElem] = elem;
            heap[nrElem] = elem;
            pos[elem] = nrElem;

            percolate(nrElem);

        } else if (actiune == 2) {
            int poz;
            fin >> poz;

//            cout << "elem sters: " << nr[poz];
            deleteElem(pos[nr[poz]]);
//            fout << "--" << nr[poz] << " -- " << heap[1] << endl;

        } else if (actiune == 3) fout << heap[1] << endl;
    }
    return 0;
}