Pagini recente » Cod sursa (job #773599) | Cod sursa (job #2507921) | Cod sursa (job #3214820) | Cod sursa (job #2144118) | Cod sursa (job #2889775)
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int dim; /// dimensiunea heap ului
int n, heap[200005], poz[200005], indici[200005];
int j, cod, x, k;
void Swap(int a, int b)
{
poz[indici[a]] = a;
poz[indici[b]] = b;
swap(heap[a], heap[b]);
swap(indici[a], indici[b]);
}
void Up(int x)
{
if(x == 1) return;
if(heap[x/2] > heap[x])
{
Swap(x , x/2);
Up(x/2);
}
}
void Down(int x)
{
int k = 0;
if( 2*x <= n)
{
k = 2*x;
if( 2*x + 1 <= n && heap[2*x +1] < heap[2*x])
k = 2*x + 1;
}
if( k > 0 && heap[k] < heap[x])
{
Swap(x, k);
Down(k);
}
}
void CreateNewHeap(int k)
{
if(k > 1 && heap[k/2] > heap[k])
Up(k);
else
Down(k);
}
void Insertion()
{
fin >> x;
dim++;
j++;
heap[dim] = x;
indici[dim] = j;
poz[j] = dim;
Up(dim);
}
void Delete()
{
fin >> x;
k = poz[x];
Swap(dim, k);
dim--;
CreateNewHeap(k);
}
void WriteMinim()
{
/// mereu radacina este elementul minim
fout << heap[1] <<"\n";
k = poz[heap[1]];
Swap(dim, k);
dim--;
CreateNewHeap(k);
}
int main()
{
fin >> n;
for(int i=1; i<=n; i++)
{
fin >> cod;
if(cod == 1)
Insertion();
else if(cod == 2)
Delete();
else
WriteMinim();
}
return 0;
}