Pagini recente » Cod sursa (job #24933) | Cod sursa (job #2790633) | Cod sursa (job #2028497) | Cod sursa (job #1586314) | Cod sursa (job #963416)
Cod sursa(job #963416)
#include <fstream>
#include <algorithm>
#define Max_Size 200009
using namespace std;
ifstream f("heapuri.in"); ofstream g("heapuri.out");
int t, tip, x, n, nr_el, poz_el[Max_Size], fr[Max_Size];
int H[Max_Size];
inline int give_father(int K)
{
return K / 2;
}
inline void percolate(int Heap[], int son)
{
int father, poz, poz1;
father = give_father(son);
bool ok = 0;
poz = poz1 = nr_el;
do
{
if(Heap[father] > Heap[son])
{
swap(Heap[father], Heap[son]);
swap(poz_el[son], poz_el[father]);
fr[father] = poz1;
//fr[son] = poz;
fr[poz] = father;
son = father;
poz1 = son;
}
father = give_father(son);
}
while(father >= 1 && Heap[father] > Heap[son]);
}
inline int left_son(int K)
{
return K * 2;
}
inline int right_son(int K)
{
return K * 2 + 1;
}
inline void sift(int Heap[], int K, int N)
{
int minim = Heap[left_son(K)], poz_min = left_son(K);
if(minim > Heap[right_son(K)]) poz_min = right_son(K),
minim = Heap[right_son(K)];
int father = K;
do
{
if(Heap[father] > Heap[poz_min])
{
swap(Heap[father], Heap[poz_min]);
swap(poz_el[father], poz_el[poz_min]);
fr[father] = poz_min;
fr[poz_min] = father;
father = poz_min;
}
minim = Heap[left_son(father)], poz_min = left_son(father);
if(minim > Heap[right_son(father)]) poz_min = right_son(father),
minim = Heap[right_son(father)];
}
while(father <= N / 2 && Heap[father] > Heap[poz_min] && poz_min <= N);
}
inline void cut(int Heap[], int N, int K)
{
Heap[K] = H[N];
N--;
if(Heap[K] < Heap[give_father(K)] && give_father(K) > 0) percolate(Heap, K);
else
if((Heap[K] > Heap[left_son(K)] && left_son(K) <= N) ||
(Heap[K] > Heap[right_son(K)] && right_son(K) <= N)) sift(Heap, K, N);
}
int main()
{
f >> t;
while(t --)
{
f >> tip;
if(tip < 3) f >> x;
switch(tip)
{
case 1 :
{
H[++n] = x;
++nr_el;
poz_el[nr_el] = nr_el;
fr[nr_el] = nr_el;
percolate(H, n);
break;
}
case 2 :
{
cut(H, n, fr[x]);
n--;
break;
}
case 3 :
{
g << H[1] << '\n';
break;
}
}
}
g.close();
return 0;
}