Pagini recente » Cod sursa (job #1052761) | Cod sursa (job #1815371) | Cod sursa (job #1698651) | Cod sursa (job #1899605) | Cod sursa (job #1990954)
#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, myV.size()));
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]);
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();
} else if (a == 1) {
fileIn >> b;
heap.insert(b);
} else {
fileIn >> b;
heap.remove(b - 1);
}
}
fileIn.close();
fileOut.close();
return 0;
}