Pagini recente » Cod sursa (job #3176713) | Cod sursa (job #722607) | Cod sursa (job #2395737) | Cod sursa (job #950780) | Cod sursa (job #2788548)
#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int CAPACITY = 200013;
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
class Heap
{
private:
int val[CAPACITY];
int kth[CAPACITY];
int nextIdx = 1;
int count = 0;
int kthIndex[CAPACITY];
void swapNodes(int idx0, int idx1)
{
swap(kthIndex[kth[idx0]], kthIndex[kth[idx1]]);
swap(kth[idx0], kth[idx1]);
swap(val[idx0], val[idx1]);
}
void heapUp(int idx)
{
if (idx == 1)
{
return;
}
if (val[idx] < val[idx / 2])
{
swapNodes(idx, idx / 2);
heapUp(idx / 2);
}
}
void heapDown(int idx)
{
int lowerBound = nextIdx - 1;
int left = idx * 2;
int right = idx * 2 + 1;
if (left > lowerBound)
{
return;
}
int minIdx = idx;
if (val[left] < val[minIdx])
{
minIdx = left;
}
if (right <= lowerBound && val[right] < val[minIdx])
{
minIdx = right;
}
if (idx != minIdx)
{
swapNodes(idx, minIdx);
heapDown(minIdx);
}
}
void deleteByIdx(int idx)
{
swapNodes(idx, nextIdx - 1);
--nextIdx;
heapDown(idx);
}
public:
void addVal(int newVal)
{
int idx = nextIdx;
val[idx] = newVal;
kth[idx] = ++count;
kthIndex[count] = idx;
++nextIdx;
heapUp(idx);
}
int top()
{
return val[1];
}
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;
}