Pagini recente » Cod sursa (job #1724259) | Cod sursa (job #1101087) | Cod sursa (job #2430195) | Cod sursa (job #1991938) | Cod sursa (job #2788543)
#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;
#define val first
#define kth second
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int CAPACITY = 200001;
class Heap
{
private:
pair<int, int> nodes[CAPACITY];
int length = 0;
int count = 0;
map<int, int> kthIndex;
void swap(int idx0, int idx1)
{
kthIndex[nodes[idx0].kth] = idx1;
kthIndex[nodes[idx1].kth] = idx0;
pair<int, int> temp = nodes[idx0];
nodes[idx0] = nodes[idx1];
nodes[idx1] = temp;
}
void heapUp(int idx)
{
pair<int, int> curr = nodes[idx];
pair<int, int> parent = nodes[idx / 2];
if (curr.val < parent.val)
{
swap(idx, idx / 2);
heapUp(idx / 2);
}
}
void heapDown(int idx)
{
int lowerBound = length - 1;
int left = idx * 2;
int right = idx * 2 + 1;
if (left > lowerBound)
{
return;
}
int minIdx = idx;
if (nodes[left].val < nodes[minIdx].val)
{
minIdx = left;
}
if (right <= lowerBound && nodes[right].val < nodes[minIdx].val)
{
minIdx = right;
}
if (idx != minIdx)
{
swap(idx, minIdx);
heapDown(minIdx);
}
}
void deleteByIdx(int idx)
{
swap(idx, length - 1);
--length;
heapDown(idx);
}
public:
void addVal(int val)
{
pair<int, int> node = {val, ++count};
kthIndex[count] = length;
nodes[length++] = node;
heapUp(length - 1);
}
int top()
{
return nodes[0].val;
}
void removeKth(int k)
{
deleteByIdx(kthIndex[k]);
}
};
int main()
{
int t, val, op, k;
Heap h;
fin >> t;
while (t-- > 0)
{
fin >> op;
if (op == 1)
{
fin >> val;
h.addVal(val);
}
else if (op == 2)
{
fin >> k;
h.removeKth(k);
}
else if (op == 3)
{
fout << h.top() << "\n";
}
}
return 0;
}