Cod sursa(job #1807552)

Utilizator preda.andreiPreda Andrei preda.andrei Data 16 noiembrie 2016 18:14:11
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>

using namespace std;

typedef vector<int> Heap;
typedef unsigned int uint;

inline uint Tata(int x) { return x / 2; }
inline uint FiuSt(int x) { return x * 2; }
inline uint FiuDr(int x) { return x * 2 + 1; }

void Percolate(Heap &h, int p)
{
    while (p > 0 && h[p] < h[Tata(p)]) {
        swap(h[p], h[Tata(p)]);
        p = Tata(p);
    }
}

void Sift(Heap &h, int p)
{
    while (p != -1) {
        int fiu = -1;
        if (FiuSt(p) < h.size()) {
            fiu = FiuSt(p);
            if (FiuDr(p) < h.size() && h[FiuDr(p)] < h[fiu]) fiu = FiuDr(p);
            if (h[fiu] < h[p])
                swap(h[fiu], h[p]);
            else fiu = -1;
        }
        p = fiu;
    }
}

void Adauga(Heap &h, vector<int> &v, int x)
{
    v.push_back(x);
    h.push_back(x);
    Percolate(h, h.size() - 1);
}

void Sterge(Heap &h, int x)
{
    for (uint i = 0; i < h.size(); ++i) {
        if (h[i] == x) {
            swap(h[i], h.back());
            h.pop_back();
            if (i != h.size()) {
                if (i > 0 && h[Tata(i)] > h[i])
                    Percolate(h, i);
                else Sift(h, i);
            }
        }
    }
}

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

    int n;
    fin >> n;

    Heap heap;
    vector<int> valori;
    while (n--) {
        int r;
        fin >> r;
        if (r == 3) {
            fout << heap[0] << "\n";
        } else {
            int x;
            fin >> x;
            if (r == 1)
                Adauga(heap, valori, x);
            else Sterge(heap, valori[x - 1]);
        }
    }

    return 0;
}