Pagini recente » Cod sursa (job #2766214) | Cod sursa (job #583179) | Cod sursa (job #1156125) | Cod sursa (job #1202239) | Cod sursa (job #1537152)
#include <fstream>
#include <algorithm>
#define NMax 200010
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int operations, vals[NMax], H[2*NMax], last, heapPos[NMax], k, num;
int leftSon(int node)
{
return 2 * node;
}
int rightSon(int node)
{
return 2 * node + 1;
}
int parent(int node)
{
return node / 2;
}
void upHeap(int node)
{
while (node > 1 && vals[H[node]] < vals[H[parent(node)]]) {
swap(heapPos[H[node]], heapPos[H[parent(node)]]);
swap(H[node], H[parent(node)]);
node = parent(node);
}
}
void downHeap(int node)
{
while (node <= last / 2) {
if (leftSon(node) < rightSon(node)) {
swap(heapPos[H[node]], heapPos[H[leftSon(node)]]);
swap(H[node], H[leftSon(node)]);
node = leftSon(node);
}
else {
swap(heapPos[H[node]], heapPos[H[rightSon(node)]]);
swap(H[node], H[rightSon(node)]);
node = rightSon(node);
}
}
}
void insertHeap(int val)
{
vals[++num] = val;
++last;
H[last] = num;
heapPos[++k] = last;
upHeap(last);
}
void deleteHeap(int ord)
{
int pos = heapPos[ord];
heapPos[H[last]] = pos;
H[pos] = H[last];
last--;
if (vals[H[pos]] < vals[H[parent(pos)]])
upHeap(pos);
else
downHeap(pos);
}
int displayMin()
{
return vals[H[1]];
}
int main()
{
f>>operations;
int op, el;
for (int i=1; i<=operations; i++) {
f >> op;
if (op == 1) {
f >> el;
insertHeap(el);
}
else if (op == 2) {
f >> el;
deleteHeap(el);
}
else
g << displayMin() << "\n";
}
return 0;
}