Pagini recente » Borderou de evaluare (job #1051039) | Cod sursa (job #70519) | Cod sursa (job #2199030) | Cod sursa (job #2136187) | Cod sursa (job #3305877)
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cmath>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
struct heapElement{
int poz, born;
long long val;
};
/*
poz - where in heap
val - value
born - when added
*/
const int maxn = 2*1e6;
heapElement heap[4*maxn+1];
int heapDim = 0, pozBorn[maxn+1], bornDim = 0;
void getMin()
{
cout << heap[1].val << "\n";
}
int parinte( int nod )
{
return (nod - (nod%2)) / 2;
}
int copil( int nod )
{
long long minn = 1LL<<60;
if( nod*2 <= heapDim && heap[nod*2].val < minn )
minn = heap[nod*2].val;
if( nod*2+1 <= heapDim && heap[nod*2+1].val < minn )
minn = heap[nod*2+1].val;
if( nod*2 <= heapDim && heap[nod*2].val == minn )
return nod*2;
if( nod*2+1 <= heapDim && heap[nod*2+1].val == minn )
return nod*2+1;
return nod*2;
}
void swapNodes(int a, int b)
{
swap(heap[a], heap[b]);
pozBorn[heap[a].born] = a;
pozBorn[heap[b].born] = b;
}
void repairUpHeap( int x )
{
int nod = x;
while( parinte(nod) != 0 && heap[nod].val < heap[parinte(nod)].val )
{
swapNodes( nod, parinte(nod) );
nod = parinte(nod);
}
}
void repairDownHeap( int x )
{
int nod = x;
while( copil(nod) <= heapDim && heap[nod].val > heap[copil(nod)].val )
{
swapNodes( nod, copil(nod) );
nod = copil(nod);
}
}
void add( int x )
{
++heapDim;
++bornDim;
heap[heapDim].val = x;
heap[heapDim].poz = heapDim;
heap[heapDim].born = bornDim;
pozBorn[bornDim] = heapDim;
repairUpHeap( heapDim );
}
void sterge( int z )
{
int unde = pozBorn[ z ];
if( unde == heapDim )
{
--heapDim;
return;
}
//cout << "\nAvem " << z << " " << pozBorn[ z ] << " " << heap[ unde ].val << "\n";
swapNodes( unde, heapDim );
--heapDim;
repairUpHeap( unde );
repairDownHeap( unde );
}
void afiseaza()
{
cout << "\nSize: " << heapDim << "\n";
int p = 1, i, j = 1;
for( i = 1; i <= heapDim; ++i )
{
cout << "{" << heap[i].val << ", " << heap[i].born << ", " << heap[i].poz << "} ";
if( i == j )
cout << "\n", p*=2, j+=p;
}
}
int main() {
ios_base::sync_with_stdio(false);
f.tie(nullptr);
g.tie(nullptr);
int m;
cin >> m;
for( int i = 1; i <= m; ++i )
{
int c;
cin >> c;
if( c == 1 )
{
long long x;
cin >> x;
add(x);
}
else if( c == 2 )
{
int x;
cin >> x;
sterge(x);
//cout << "Hopa";
}
else
getMin();
//afiseaza();
}
return 0;
}