Cod sursa(job #2741631)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 16 aprilie 2021 21:27:33
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

vector <int> heap;
vector <int> elemente;

void urca(int poz) {
    while (poz) {
    int tata = (poz - 1) / 2;
        if (heap[tata] > heap[poz]) {
            swap(heap[tata], heap[poz]);
                poz = tata;
        }

        else {
            break;
        }

}

}

void coboara(int poz) {
    if (poz * 2 + 1 >= heap.size())
        return;

    int fiu_st = heap[poz * 2 + 1];

    if ((poz * 2 + 2 == heap.size()) || fiu_st < heap[poz * 2 + 2])
        if (fiu_st < heap[poz])
            {
            swap(heap[poz], heap[poz * 2 + 1]);

            coboara(poz * 2 + 1);

            return;
            }

        else return;


    else
        if (heap[poz * 2 + 2] < heap[poz]) {

            swap(heap[poz], heap[poz * 2 + 2]);

            coboara(poz * 2 + 2);

            return;
            }

        else
            return;


}

void push(int x) {

    heap.push_back(x);
    urca(heap.size()-1);
}

int pop(){
    if (heap.size() == 0)
        return -1;

    int vf = heap[0];

    heap[0] = heap[heap.size()-1];

    heap.pop_back();

    coboara(0);

    return 0;
}

void elimina(int i) {
    heap[i] = heap[heap.size() - 1];

    heap.pop_back();

    coboara(i);

    urca(i);
}


int main()
{
    elemente.push_back(-123456);

    int N, optiune, element, index;

    f >> N;

    for (int i = 0; i < N; i++)
        {f >> optiune;
        if (optiune == 1)
        {
            f >> element;
            push(element);
            int k;
            elemente.push_back(element);
        }
        else
            if (optiune == 2)
                {f >> index;
                 unsigned j;
                 for (j = 0; j < elemente.size(); j++)
                    if (heap[j] == elemente[index])
                        break;
                 elimina(j);
                 int k;


                }
            else
                if (optiune == 3)
                    g << heap[0] << "\n";
        }
    return 0;
}