Pagini recente » Cod sursa (job #1197491) | Cod sursa (job #1466999) | Cod sursa (job #64756) | Cod sursa (job #902939) | Cod sursa (job #2739441)
#include <bits/stdc++.h>
# define Nmax 200005
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int n, l, nr;
int h[Nmax], a[Nmax], poz[Nmax];
/// h este un heap de minim
/// in h punem indicii din a si ii sortam dupa a[h[i]]
/// poz[i] = x <=> a[i] este pe pozitia x in h
/// ! la toti vectorii avem indexare de la 1
inline int father(int nod){ /// functia returneaza indicele tatalui lui nod
return nod / 2;
}
inline int left(int nod){ /// functia returneaza indicele fiului stanga a lui nod
return nod * 2 + 1;
}
inline int right(int nod){ /// functia returneaza indicele fiului dreapta a lui nod
return nod * 2 + 2;
}
void percolate(int k)
{
if (k > 0){ /// daca mai putem urca
int tata = father(k);
if (a[h[tata]] > a[h[k]]){
swap(h[tata], h[k]);
swap(poz[h[k]], poz[h[tata]]);
percolate(tata);
}
}
}
void sift(int k)
{
int st = left(k);
int dr = right(k);
int son = k;
if (st < l && a[h[st]] < a[h[son]]) son = st;
if (dr < l && a[h[dr]] < a[h[son]]) son = dr; /// alegem cel mai mic fiu
if (son != k){
swap(h[k], h[son]);
swap(poz[h[k]], poz[h[son]]);
sift(son);
}
}
void Insert(int x)
{
h[l] = x;
poz[h[l]] = l;
percolate(l);
l ++;
}
void Extract(int k)
{
k = poz[k];
swap(h[k], h[l - 1]);
swap(poz[h[k]], poz[h[l - 1]]);
l--;
sift(k);
percolate(k);
}
int main()
{ int cmd, val;
fin>>n;
for(int i = 0; i < n; i ++){
fin>>cmd;
if(cmd == 1){
fin>>val;
a[nr ++] = val;
Insert(nr - 1);
}
if(cmd == 2){
fin>>val;
Extract(val - 1);
}
if(cmd == 3) fout << a[h[0]] << "\n";
}
return 0;
}