Pagini recente » Cod sursa (job #2811591) | Cod sursa (job #1945612) | Cod sursa (job #2852921) | Cod sursa (job #1388525) | Cod sursa (job #1397332)
#include <fstream>
#define father(x) x / 2
#define left_son(x) 2 * x
#define right_son(x) 2 * x + 1
using namespace std;
fstream f("heapuri.in", ios::in);
fstream g("heapuri.out", ios::out);
const int nmax = 200010;
int t, n, m, i, j, q, x, p, a[nmax], h[nmax], poz[nmax];
void swap(int x, int y)
{
int aux;
poz[h[x]] = y;
poz[h[y]] = x;
aux = h[x];
h[x] = h[y];
h[y] = aux;
}
void up(int nod)
{
while ((nod > 1) && (a[h[nod]] < a[h[father(nod)]]))
{
swap(nod, father(nod));
nod = father(nod);
}
}
void down(int nod)
{
int sch = 1, son;
while ((left_son(nod) <= n) && (sch))
{
sch = 0;
son = left_son(nod);
if ((right_son(nod) <= n) && (a[h[right_son(nod)]] < a[h[left_son(nod)]]))
{
son = right_son(nod);
}
if (a[h[son]] < a[h[nod]])
{
sch = 1;
swap(nod, son);
nod = son;
}
}
}
int main()
{
f >> t;
for (i = 1; i <= t; i++)
{
f >> q;
if (q == 1) // push
{
f >> x;
n++;
m++;
a[m] = x;
h[n] = m;
poz[m] = n;
up(n);
}
if (q == 2) //pop
{
f >> x;
p = poz[x];
swap(p, n);
n--;
if ((p > 1) && (a[h[father(p)]] > a[h[p]]))
{
up(p);
}
else
{
down(p);
}
}
if (q == 3)
{
g << a[h[1]] << '\n';
}
}
return 0;
}