Cod sursa(job #2819976)

Utilizator DanielRusuDaniel Rusu DanielRusu Data 19 decembrie 2021 15:49:30
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include <fstream>

using namespace std;

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

#define DIM 200003

struct elem{
    int value;
    int th;
} heap[DIM];

bool aFostEliminat[DIM];
int heapSize;

int indexElemente;

void inserare(int element);
void afisareMinim();
void sterge();

int main() {

    int N;
    fin >> N;

    int operatie, x;
    while(N > 0) {
        N--;
        fin >> operatie;

        if(operatie == 1) {
            fin >> x;
            inserare(x);
        }
        else if(operatie == 2) {
            fin >> x;
            aFostEliminat[x] = true;
        }
        else {

            afisareMinim();
        }
    }

    return 0;
}

void inserare(int element) {
    indexElemente++;

    elem elementNou;
    elementNou.value = element;
    elementNou.th = indexElemente;

    heapSize++;
    heap[heapSize] = elementNou;

    int position = heapSize;
    while(position != 1 &&
          heap[position].value < heap[position / 2].value)
    {

        swap(heap[position], heap[position / 2]);
        position /= 2;
    }
}

void afisareMinim() {

    while(heapSize > 0 && aFostEliminat[heap[1].th]) {

        sterge();
    }

    fout << heap[1].value << '\n';
}

void sterge() {
    heap[1] = heap[heapSize];
    heapSize--;

    int position = 1;

    while(true) {

        elem stang, drept;
        bool existaStang = false, existaDrept = false;

        if(position * 2 <= heapSize) {
            stang = heap[position * 2];
            existaStang = true;
        }

        if(position * 2 + 1 <= heapSize) {
            existaDrept = true;
            drept = heap[position * 2 + 1];
        }

        bool flag = false;
        if(!existaDrept && !existaStang) break;
        if(!existaDrept && existaStang) {

            if(heap[position].value > stang.value) {

                swap(heap[position], heap[position * 2]);
                flag = true;
            }
        }
        if(existaDrept && existaStang) {

            if(stang.value < drept.value) {
                /// Mai mic e stangul
                if(heap[position].value > stang.value) {

                    swap(heap[position], heap[position * 2]);
                    flag = true;
                }
            }
            else {
                if(heap[position].value > drept.value) {

                    swap(heap[position], heap[position * 2 + 1]);
                    flag = true;
                }
            }
        }

        if(!flag) {
            break;
        }
    }
}