Cod sursa(job #1990960)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 14 iunie 2017 13:52:34
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <fstream>
#include <vector>
#include <utility>

class Heap {
    std::vector<int> pos;
    std::vector<std::pair<int, int>> myV;
public:
    void insert(int val) {
        pos.push_back(myV.size());
        myV.push_back(std::make_pair(val, pos.size() - 1));
        upheap(pos.back());
    }
    void upheap(int ind) {
        if (!ind) {
            return;
        }
        int parent = (ind - 1) / 2;
        if (myV[parent].first > myV[ind].first) {
            std::swap(pos[myV[parent].second], pos[myV[ind].second]);
            std::swap(myV[parent], myV[ind]);
            upheap(parent);
        }
    }
    void downheap(int ind) {
        int left = ind * 2 + 1;
        int right = left + 1;
        int mover = ind;
        if (left < myV.size() && myV[left].first < myV[mover].first) {
            mover = left;
        }
        if (right < myV.size() && myV[right].first < myV[mover].first) {
            mover = right;
        }
        if (mover != ind) {
            std::swap(pos[myV[ind].second], pos[myV[mover].second]);
            std::swap(myV[ind], myV[mover]);
            downheap(mover);
        }
    }
    void remove(int ind) {
        int delPos = pos[ind];
        if (delPos == (myV.size() - 1)) {
            myV.pop_back();
            return;
        }
        std::swap(pos[myV[delPos].second], pos[myV[myV.size() - 1].second]);
        std::swap(myV[delPos], myV[myV.size() - 1]);
        myV.pop_back();
        downheap(delPos);
    }
    int top() {
        return myV.front().first;
    }
};

int main() {
    std::ifstream fileIn("heapuri.in");
    std::ofstream fileOut("heapuri.out");

    int nV, a, b;

    fileIn >> nV;

    Heap heap;

    for (; nV > 0; nV--) {
        fileIn >> a;
        if (a == 3) {
            fileOut << heap.top() << '\n';
        } else if (a == 1) {
            fileIn >> b;
            heap.insert(b);
        } else {
            fileIn >> b;
            heap.remove(b - 1);
        }
    }

    fileIn.close();
    fileOut.close();
    return 0;
}