Pagini recente » Cod sursa (job #1396833) | Cod sursa (job #2344294) | Cod sursa (job #2305867) | Cod sursa (job #2524656) | Cod sursa (job #2895342)
#include <fstream>
#include <utility>
#include <vector>
std::ifstream fin("heapuri.in");
std::ofstream fout("heapuri.out");
int N, Op, Val, Dim, Ord, Poz;
std::vector<int> Pozitii(200001);
std::vector< std::pair<int, int> > Heap(200001);
void inserare()
{
Dim++;
Ord++;
Heap[Dim].first = Val; // Valoarea elementului din heap
Heap[Dim].second = Ord; // Al catelea a fost inserat in heap
Pozitii[Ord] = Dim; // Pozitia pe care se afla elementul inserat al x-lea in heap
Poz = Dim;
while (Poz > 1 && Heap[Poz] < Heap[Poz / 2])
{
std::swap(Heap[Poz], Heap[Poz / 2]);
std::swap(Pozitii[Heap[Poz].second], Pozitii[Heap[Poz / 2].second]);
Poz /= 2;
}
}
void stergere()
{
Poz = Pozitii[Val];
std::swap(Heap[Poz], Heap[Dim]);
std::swap(Pozitii[Heap[Poz].second], Pozitii[Heap[Dim].second]);
Dim--;
int Fiu;
do
{
Fiu = 0;
if (Poz * 2 <= Dim)
{
Fiu = Poz * 2;
if (Poz * 2 + 1 <= Dim && Heap[Poz * 2 + 1] < Heap[Poz * 2])
{
Fiu = Poz * 2 + 1;
}
if (Heap[Fiu] >= Heap[Poz])
{
Fiu = 0;
}
}
if (Fiu)
{
std::swap(Heap[Poz], Heap[Fiu]);
std::swap(Pozitii[Heap[Poz].second], Pozitii[Heap[Fiu].second]);
Poz = Val;
}
} while (Fiu);
}
int main()
{
fin >> N;
for (int i = 0; i < N; i++)
{
fin >> Op;
switch (Op)
{
case 1:
fin >> Val;
inserare();
break;
case 2:
fin >> Val;
stergere();
break;
case 3:
fout << Heap[1].first << '\n';
break;
default:
break;
}
}
}