Pagini recente » Cod sursa (job #2673336) | Cod sursa (job #271883) | Cod sursa (job #1650241) | Cod sursa (job #2077526) | Cod sursa (job #2893280)
#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();
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;
int i = nheap - 1;
while (i != 0 && val[heap[i / 2]] > val[heap[i]])
{
swap(heap[i / 2], heap[i]);
swap(pos[heap[i / 2]], pos[heap[i]]);
i /= 2;
}
}
void Heap::del(int x)
{
--x;
swap(heap[nheap - 1], heap[pos[x]]);
//cout << pos[n - 1] << " " << pos[x] << endl;
swap(pos[heap[nheap - 1]], pos[x]);
nheap--;
int i = pos[x];
int next = -1;
while (next != i)
{
next = i;
//print();
bool child1 = false;
bool child2 = false;
if (i != 0 && val[heap[i]] < val[heap[i / 2]])
next = i / 2;
if (2 * i < nheap && val[heap[2 * i]] < val[heap[i]])
child1 = true;
if (2 * i + 1 < nheap && val[heap[2 * i + 1]] < val[heap[i]])
child2 = true;
if (child1 && child2)
{
if (val[heap[2 * i]] < val[heap[2 * i + 1]])
next = 2 * i;
else
next = 2 * i + 1;
}
else if (child1)
{
next = 2 * i;
}
else if (child2)
{
next = 2 * i + 1;
}
swap(heap[i], heap[next]);
swap(pos[heap[i]], pos[heap[next]]);
}
}
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();
}
}