Pagini recente » Cod sursa (job #1068292) | Cod sursa (job #1770905) | Cod sursa (job #2475551) | Cod sursa (job #2705598) | Cod sursa (job #2815179)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector <int> heap(1, 0), poz(1, 0), v(1, 0);
int k;
const int NMAX = 200005;
bool empty()
{
return (heap.size() == 1);
}
void insert(int x)
{
int pos = heap.size();
heap.push_back(++k);
v.push_back(x);
poz.push_back(k);
while(pos / 2 >= 1)
{
if(v[heap[pos]] < v[heap[pos / 2]])
{
swap(poz[heap[pos]], poz[heap[pos / 2]]);
swap(heap[pos], heap[pos / 2]);
}
else
break;
pos = pos / 2;
}
}
void pop(int x)
{
int pos = poz[x], ok = 1, aux;
aux = heap[heap.size() - 1];
swap(heap[poz[x]], heap[heap.size() - 1]);
swap(poz[x], poz[aux]);
heap.pop_back();
aux = pos;
while(pos / 2 >= 1)
{
if(v[heap[pos]] < v[heap[pos / 2]])
{
swap(poz[heap[pos]], poz[heap[pos / 2]]);
swap(heap[pos], heap[pos / 2]);
ok = 0;
}
else
break;
pos = pos / 2;
}
pos = aux;
if(ok)
{
int pos_min;
while(pos * 2 < heap.size())
{
pos_min = -1;
if(v[heap[pos]] > v[heap[pos * 2]])
pos_min = pos * 2;
if(pos * 2 + 1 < heap.size() && v[heap[pos]] > v[heap[pos * 2 + 1]] && v[heap[pos * 2 + 1]] < v[heap[pos * 2]])
pos_min = pos * 2 + 1;
if(pos_min == -1)
break;
swap(poz[heap[pos]], poz[heap[pos_min]]);
swap(heap[pos], heap[pos_min]);
pos = pos_min;
}
}
}
int top()
{
return v[heap[1]];
}
int main()
{
int m, i, op, x;
fin >> m;
while(m--)
{
fin >> op;
if(op == 1)
{
fin >> x;
insert(x);
}
else if(op == 2)
{
fin >> x;
pop(x);
}
else
{
fout << top() << '\n';
}
}
return 0;
}