Pagini recente » Cod sursa (job #578188) | Cod sursa (job #1075404) | Cod sursa (job #1672038) | Cod sursa (job #2477363) | Cod sursa (job #2760078)
#include <iostream>
#include <fstream>
using namespace std;
const int N = 200001;
int heap[N], pozitie[N], nr_el, v[N];
void urcare(int poz){
while (v[heap[poz]] < v[heap[(poz - 1)/ 2]]){
int aux = heap[(poz - 1) / 2];
heap[(poz - 1) / 2] = heap[poz];
heap[poz] = aux;
pozitie[heap[(poz - 1) / 2]] = (poz - 1) / 2;
pozitie[heap[poz]] = poz;
poz = (poz - 1) / 2;
}
}
void coborare(int poz){
int fiu, p = poz;
fiu = poz * 2 + 1;
if (fiu < nr_el && v[heap[fiu]] < v[heap[p]]){
p = fiu;
}
fiu = poz * 2 + 2;
if (fiu < nr_el && v[heap[fiu]] < v[heap[p]]){
p = fiu;
}
if (p != poz){
int aux = heap[poz];
heap[poz] = heap[p];
heap[p] = aux;
pozitie[heap[p]] = p;
pozitie[heap[poz]] = poz;
coborare(p);
}
}
void inserare(int el){
heap[nr_el++] = el;
pozitie[el] = nr_el - 1;
urcare(nr_el - 1);
}
void stergere(int poz){
///inlocuire cu elementul de dupa heap
if (poz == nr_el - 1)
{
nr_el--;
}
else
{
heap[poz] = heap[nr_el - 1];
nr_el--;
pozitie[heap[poz]] = poz;
coborare(poz);
urcare(poz);
}
///heap[pozitie[poz]] = heap[nr_el++]; ??
///heap[pozitie[poz]] = heap[nr_el]; nr_el--; ??
coborare(pozitie[poz]);
}
int main()
{
ifstream fi ("heapuri.in");
ofstream fo ("heapuri.out");
int nr_op, n = 0;
fi >> nr_op;
for (int i = 0; i < nr_op; i++){
int tip;
fi >> tip;
if (tip == 1){
int x;
fi >> x;
v[n++] = x;
inserare(n - 1);
} else if (tip == 2){
int x;
fi >> x;
x--;
stergere(pozitie[x]);
} else {
fo << v[heap[0]] << "\n";
}
/*
for (int j = 0; j < nr_el; j++)
{
fo << v[heap[j]] << " ";
}
fo << "\n";
*/
}
fi.close();
fo.close();
return 0;
}