Cod sursa(job #2742391)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 20 aprilie 2021 21:06:24
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <unordered_map>

using namespace std;

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

vector <int> heap;
vector <int> elemente;
unordered_map <int, int> where;

void urca(int poz) {
    while (poz) {
    int tata = (poz - 1) / 2;
        if (heap[tata] > heap[poz]) {
            swap(heap[tata], heap[poz]);
            where[heap[tata]] = tata;
            where[heap[poz]] = 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]);
            where[heap[poz * 2 + 1]] = poz * 2 + 1;
            where[heap[poz]] = poz;

            coboara(poz * 2 + 1);

            return;
            }

        else return;


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

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


            coboara(poz * 2 + 2);

            return;
            }

        else
            return;


}

void push(int x) {

    heap.push_back(x);
    where[x] = heap.size() - 1;
    urca(heap.size()-1);
}

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

    int vf = heap[0];



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

    where[heap[0]] = 0;

    heap.pop_back();

    coboara(0);

    return 0;
}

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

    where[heap[i]] = i;

    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;

                 elimina(where[elemente[index]]);

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

    return 0;
}