Pagini recente » Cod sursa (job #1460538) | Cod sursa (job #1638825) | Cod sursa (job #166417) | Cod sursa (job #2832245) | Cod sursa (job #2893324)
#include <iostream>
#include <fstream>
#include <array>
using namespace std;
/*ifstream in("input.txt");
ofstream out("output.txt");*/
ifstream in("heapuri.in");
ofstream out("heapuri.out");
const int HEAP_SIZE = 200002;
class Heap
{
public:
Heap() : heap(array<int, HEAP_SIZE>{}),
pos(array<int, HEAP_SIZE>{}),
nheap(0), npos(0) {}
void insert(int x);
void del(int x);
int getMin();
void print();
void up(int x);
void down(int x);
private:
array<int, HEAP_SIZE> heap;
array<int, HEAP_SIZE> pos;
array<int, HEAP_SIZE> val;
int nheap, npos;
};
void Heap::insert(int x)
{
heap[nheap] = npos;
pos[npos] = nheap;
val[npos] = x;
++npos;
++nheap;
up(nheap - 1);
}
void Heap::up(int x)
{
int i = x;
while (i != 0 && val[heap[i / 2]] > val[heap[i]])
{
swap(heap[i / 2], heap[i]);
pos[heap[i / 2]] = i / 2, pos[heap[i]] = i;
i /= 2;
}
}
void Heap::down(int x)
{
int y = -1;
while (x != y)
{
y = x;
if (2 * y < nheap && val[heap[x]] > val[heap[2 * y]])
x = 2 * y;
if (2 * y + 1 < nheap && val[heap[x]] > val[heap[y * 2 + 1]])
x = 2 * y + 1;
swap(heap[x], heap[y]);
pos[heap[x]] = x, pos[heap[y]] = y;
}
}
void Heap::del(int x)
{
--x;
heap[pos[x]] = heap[nheap - 1];
// cout << pos[n - 1] << " " << pos[x] << endl;
nheap--;
int i = pos[x];
if (pos[x] == nheap)
return;
if (val[heap[i]] < val[heap[i / 2]])
up(i);
else
down(i);
}
int Heap::getMin()
{
return val[heap[0]];
}
void Heap::print()
{
for (int i = 0; i < nheap; ++i)
cout << val[heap[i]] << " ";
cout << endl;
}
int main()
{
Heap h;
int n;
in >> n;
for (int i = 0; i < n; ++i)
{
int query, x;
in >> query;
switch (query)
{
case 1:
in >> x;
h.insert(x);
break;
case 2:
in >> x;
h.del(x);
break;
default:
out << h.getMin() << endl;
}
//h.print();
}
}